没有前导零Calendar.MINUTE给分钟 [英] Calendar.MINUTE giving minutes without leading zero

查看:1802
本文介绍了没有前导零Calendar.MINUTE给分钟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我使用下面code得到adnroid手机的时间,但它给我分钟再予不为零,如果分钟再予是1到9。 例如:现在我有时间我的设备12:09上,但它给我的12:9

 日历C = Calendar.getInstance();
INT小时= c.get(Calendar.HOUR);
INT mnts = c.get(Calendar.MINUTE);
串CURTIME =+小时+:+ mnts;
返回CURTIME;
 

在上面code我也试着code以下的给予同样的事情上面,不分钟再予零号之前,在1到9分钟再予。 。

 最后的日历CAL = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis的());
日期日期= cal.getTime();
INT mHour = date.getHours();
INT mMinute = date.getMinutes();
 

解决方案

正如叶戈尔说,一个 INT 仅仅是一个整数。整数没有前导零。他们只能是显示的前导零,当你将它们转换为字符串的对象。做到这一点的方法之一是这样的:

 字符串CURTIME =的String.Format(%02D:%02D,小时,mnts);
 

格式字符串%02D 格式的前导零的整数(这就是 0 %02D ),始终占据2宽度的数字(这就是 2 %02D )。

这将产生字符串

  

12:09

Hi all I am using below code to get adnroid phone time,but it giving me minuts without zero if the minuts are in between 1 to 9. for example:right now I have time on my device 12:09 but its giving me as 12:9

Calendar c = Calendar.getInstance();
int hrs = c.get(Calendar.HOUR);
int mnts = c.get(Calendar.MINUTE);
String curTime = "" + hrs + ":" + mnts;
return curTime;

after above code I also try below code its giving same thing as above,minuts without zero before number it the minuts in between 1 to 9 . .

final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
Date date = cal.getTime();
int mHour = date.getHours();
int mMinute = date.getMinutes();

解决方案

As Egor said, an int is just an integer. Integers don't have leading zeros. They can only be displayed with leading zeros when you convert them to String objects. One way to do that is like this:

String curTime = String.format("%02d:%02d", hrs, mnts);

The format string %02d formats an integer with leading zeros (that's the 0 in %02d), always taking up 2 digits of width (that's the 2 in %02d).

That would produce the String

12:09

这篇关于没有前导零Calendar.MINUTE给分钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆