0

我有一个长值,其值如下所示,

例如

timeInLong = 1000 (which means 10:00 AM)
timeInLong = 1337 (which means 01:37 PM)

string我需要一种聪明的方法来转换上述类型的值并将时间格式设置为上午 10:00 和下午 01:37 。

有人可以告诉我该怎么做吗?

4

6 回答 6

4

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

于 2013-08-21T07:17:22.170 回答
1

我会做这样的事情:

SimpleDateFormat formatA = new SimpleDateFormat("hhmm");
SimpleDateFormat formatB = new SimpleDateFormat("hh:mm a");
Date intermediate = formatA.parse(String.valueOf(1337));
String result = formatB.format(intermediate);
于 2013-08-21T07:21:11.470 回答
1
    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()));
于 2013-08-21T07:29:30.727 回答
1

尝试:

SimpleDateFormat readerFormat = "HHmm";
SimpleDateFormat writerFormat = "hh:mma";

Date date = readerFormat.parse(Long.toString(timeInLong));
String toPrint = writerFormat.format(date);
于 2013-08-21T07:17:32.330 回答
0

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?

于 2013-08-21T07:17:30.297 回答
0

如果您想避免 SimpleDateFormat 导入,另一种高效的 oneliner:

String toTimeString(long time) {
    return ((time < 1300) ? time / 100 : time / 100 - 12)
         + ":" + time % 100
         + ((time < 1200) ? " AM" : " PM");
}
于 2013-08-21T07:29:12.870 回答