我有一个长值,其值如下所示,
例如
timeInLong = 1000 (which means 10:00 AM)
timeInLong = 1337 (which means 01:37 PM)
string
我需要一种聪明的方法来转换上述类型的值并将时间格式设置为上午 10:00 和下午 01:37 。
有人可以告诉我该怎么做吗?
我有一个长值,其值如下所示,
例如
timeInLong = 1000 (which means 10:00 AM)
timeInLong = 1337 (which means 01:37 PM)
string
我需要一种聪明的方法来转换上述类型的值并将时间格式设置为上午 10:00 和下午 01:37 。
有人可以告诉我该怎么做吗?
Code -
Long timeInLong = 1000l;
SimpleDateFormat dateFormat = new SimpleDateFormat("HHmm");
Date date = dateFormat.parse(Long.toString(timeInLong));
System.out.println(new SimpleDateFormat("hh:mm a").format(date));
Result -
10:00 AM
我会做这样的事情:
SimpleDateFormat formatA = new SimpleDateFormat("hhmm");
SimpleDateFormat formatB = new SimpleDateFormat("hh:mm a");
Date intermediate = formatA.parse(String.valueOf(1337));
String result = formatB.format(intermediate);
int timeInLong = 1337;
Calendar c = Calendar.getInstance();
c.set(Calendar.MINUTE, timeInLong % 100);
c.set(Calendar.HOUR_OF_DAY, timeInLong / 100);
System.out.println(new SimpleDateFormat("HH:mm a", Locale.US).format(c.getTime()));
尝试:
SimpleDateFormat readerFormat = "HHmm";
SimpleDateFormat writerFormat = "hh:mma";
Date date = readerFormat.parse(Long.toString(timeInLong));
String toPrint = writerFormat.format(date);
It seams too easy, but what about:
int hours = timeInLong / 100;
int minutes = timeInLong % 100;
boolean isPM = false;
if (hours > 12) {
isPM = true
}
if (hours > 13) {
hours -= 12;
}
String result = String.format("%02d:%02d %s", hours, minutes, (isPM ? "PM" : "AM"));
Did I miss something?
如果您想避免 SimpleDateFormat 导入,另一种高效的 oneliner:
String toTimeString(long time) {
return ((time < 1300) ? time / 100 : time / 100 - 12)
+ ":" + time % 100
+ ((time < 1200) ? " AM" : " PM");
}