开发者

How to use time format on Java

开发者 https://www.devze.com 2023-04-07 15:13 出处:网络
I have 2 variables: first variable for hours and second variable for minutes. But format for this data is \"24 hours\", but I need resulti开发者_Python百科ng string similar \"5:30 pm\".

I have 2 variables: first variable for hours and second variable for minutes. But format for this data is "24 hours", but I need resulti开发者_Python百科ng string similar "5:30 pm".

How can I format my time for this format?


Since you already have the hours and minutes as variables, date and date format objects might be overkill. You can use a method like this:

public String getTimeString(int hours, int minutes)
{
    String AmPm = "AM";
    if(hours > 12)
    {
        hours -= 12;
        AmPm = "PM";
    }
    return String.format("%d:%02d %s", hours, minutes, AmPm);
}


public static void main(String[] args) {
    formatTime(1, 23);
    formatTime(11, 33);
    formatTime(14, 43);
}

private static void formatTime(int hours, int minutes) {
    Calendar calendar = new GregorianCalendar();
    calendar.set(Calendar.HOUR, hours);
    calendar.set(Calendar.MINUTE, minutes);

    SimpleDateFormat df = new SimpleDateFormat("hh:mm a");
    System.out.println(df.format(calendar.getTime()));
}

Output will be:

01:23 PM
11:33 PM
02:43 AM

0

精彩评论

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