开发者

Problem with time format

开发者 https://www.devze.com 2023-03-17 06:25 出处:网络
I wrote the following code to get the time public String getTime() { final Calendar cld = Calendar.getInstance();

I wrote the following code to get the time

public String getTime() {
    final Calendar cld = Calendar.getInstance();
    String time = cld.get(Calendar.HOUR) + ":" + (cld.get(Calendar.MINUTE));
    try {
        Date date = new SimpleDateFormat("HH:mm").parse(time);
        time = new SimpleDateFormat("HH:mm").format(date);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.pr开发者_如何学PythonintStackTrace();
    }

    return time;
}

This always give me time like

11:59

01:07

But I need in 24 hrs format like:

11:59

13:07

How to change the code.


Use HOUR_OF_DAY instead of HOUR.


Use Calendar.HOUR_OF_DAY instead.


Calendar.HOUR = Field number for get and set indicating the hour of the morning or afternoon. HOUR is used for the 12-hour clock. E.g., at 10:04:15.250 PM the HOUR is 10.

Calendar.HOUR_OF_DAY = Field number for get and set indicating the hour of the day. HOUR_OF_DAY is used for the 24-hour clock. E.g., at 10:04:15.250 PM the HOUR_OF_DAY is 22.


Here's the code:

Calendar cal = Calendar.getInstance();
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
String time = hour + ":" + minute;


HH:mm is correct. 01:07 is 1am and 13:07 is 1pm. Wait until 1pm and see or create a date object and test it.

0

精彩评论

暂无评论...
验证码 换一张
取 消