How to set time to 24 hour format in Calendar

后端 未结 9 1457
迷失自我
迷失自我 2020-12-25 12:10

I need to set the time on the current date. The time string is always in 24 hour format but the result I get is wrong:

  SimpleDateFormat df = new SimpleDate         


        
9条回答
  •  无人及你
    2020-12-25 12:55

    tl;dr

    LocalTime.parse( "10:30" )  // Parsed as 24-hour time.
    

    java.time

    Avoid the troublesome old date-time classes such as Date and Calendar that are now supplanted by the java.time classes.

    LocalTime

    The java.time classes provide a way to represent the time-of-day without a date and without a time zone: LocalTime

    LocalTime lt = LocalTime.of( 10 , 30 );  // 10:30 AM.
    LocalTime lt = LocalTime.of( 22 , 30 );  // 22:30 is 10:30 PM.
    

    ISO 8601

    The java.time classes use standard ISO 8601 formats by default when generating and parsing strings. These formats use 24-hour time.

    String output = lt.toString();
    

    LocalTime.of( 10 , 30 ).toString() : 10:30

    LocalTime.of( 22 , 30 ).toString() : 22:30

    So parsing 10:30 will be interpreted as 10:30 AM.

    LocalTime lt = LocalTime.parse( "10:30" );  // 10:30 AM.
    

    DateTimeFormatter

    If you need to generate or parse strings in 12-hour click format with AM/PM, use the DateTimeFormatter class. Tip: make a habit of specifying a Locale.

提交回复
热议问题