没有前导零Calendar.MINUTE给分钟前导、Calendar、MINUTE

2023-09-05 02:50:33 作者:醉逍遥

大家好,我使用下面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);
 
fullcalendar 显示的时间间隔只有四十五分钟 时间和位移

格式字符串%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