Calendar Constructor Java toString

前端 未结 5 1403
天命终不由人
天命终不由人 2021-01-21 01:30

What I\'m trying to do is pass a date into the Calendar so that it will format the date ready for use with another constructor. So that i can make use of it later using the func

5条回答
  •  逝去的感伤
    2021-01-21 02:07

    LocalDate

    Apparently you want a date-only value without a day-of-time. For that use the LocalDate class rather than Calendar. The Calendar class was for a date plus a time-of-day. Furthermore, Calendar is now legacy, supplanted by the java.time classes after having proven to be troublesome, confusing, and flawed.

    Simply pass the desired year, month, and day-of-month to a factory method. The month is sanely numbered 1-12 for January-December unlike Calendar.

    LocalDate ld = LocalDate.of( 2012 , 10 , 20 );
    

    Or, pass a constant for month.

    LocalDate ld = LocalDate.of( 2012 , Month.OCTOBER , 20 );
    

    The java.time classes tend to use static factory methods rather than constructors with new.

    Strings

    To generate a string in standard ISO 8601 format, call toString

    String output = ld.toString() ;
    

    2012-10-20

    For other formats, search Stack Overflow for DateTimeFormatter. For example:

    DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
    String output = ld.format( f );
    

    20/10/2012

提交回复
热议问题