convert a 4-digit military time into the standard 12 hour time format

前端 未结 4 2030
半阙折子戏
半阙折子戏 2020-12-18 03:53

What I\'m trying to do:

I\'m trying to convert a 4-digit military time into the standard 12 hour time format, with a colon and an added PM or AM wit

4条回答
  •  没有蜡笔的小新
    2020-12-18 04:35

    You can do this much, much simpler, using a clever string conversion and SimpleDateFormat, here is the example but parsed in two lines:

    // Heres your military time int like in your code sample
    int milTime = 56;
    // Convert the int to a string ensuring its 4 characters wide, parse as a date 
    Date date = new SimpleDateFormat("hhmm").parse(String.format("%04d", milTime));
    // Set format: print the hours and minutes of the date, with AM or PM at the end 
    SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a");
    // Print the date!
    System.out.println(sdf.format(date));
    // Output: 12:56 AM
    

提交回复
热议问题