我想在应用中显示设备的当前时间。以下是代码是时间,但问题是如果当前时间是12:15但我的变量cTime有相反的时间是00:15。以下是我的时间代码,请帮帮我
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
Calendar c = Calendar.getInstance();
int currentHour = c.get(Calendar.HOUR);
int currentMin = c.get(Calendar.MINUTE);
String currentTime = currentHour+":"+currentMin;
Date cTime = sdf.parse(currentTime);
答案 0 :(得分:1)
您应该使用Calendar.HOUR_OF_DAY
代替Calendar.HOUR
来获取0-24格式的小时。
答案 1 :(得分:0)
在当前时间试用此代码
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("h:mm aa");
String datetime = sdf.format(now);
答案 2 :(得分:0)
使用这个简单的方法获取设备当前时间(以milisecound为单位)
System.currentTimeMillis();
答案 3 :(得分:0)
始终 始终 阅读documentation以了解您正在使用的代码。
您使用H
模式格式化您的营业时间,该模式描述了24小时模型:
H |一天中的小时| (0-23)|号码| 0
您需要使用小h
,代表“上午/下午(1-12)”:
SimpleDateFormat format = new SimpleDateFormat("hh:mm");
Date date = new Date();
String dateReadable = format.format(date);
// Use your String elsewhere.
这就是你开始所需要的一切。无需为此创建int
和Calendar
s。您也可以将a
作为期间指标,如下面的Arjun所述。
这也是this answer的基础,但考虑到代码略有不同而且您遇到困难(通过查看代码),我认为它不重复。