How to format a date in java?

前端 未结 4 2006
深忆病人
深忆病人 2020-12-20 10:37

How can change this date format \"2011-09-07T00:00:00+02:00\" into the \"dd.MM.\" i.e \"07.09.\"

Thanks in advance!

4条回答
  •  南笙
    南笙 (楼主)
    2020-12-20 11:10

    tl;dr

    OffsetDateTime.parse( "2011-09-07T00:00:00+02:00" ).format( DateTimeFormatter.ofPattern( "dd.MM" )
    

    java.time

    The Question and other Answers use old legacy classes that have proven to be troublesome and confusing. They have been supplanted by the java.time classes.

    Your input string is in standard ISO 8601 format. These formats are used by default in java.time classes. So no need to specify a formatting pattern.

    OffsetDateTime odt = OffsetDateTime.parse( "2011-09-07T00:00:00+02:00" );
    

    You can generate a String in your desired format.

    DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd.MM" );
    String output = odt.format( f );
    

    MonthDay

    You want month and day-of-month. There is actually a class for that, MonthDay.

    MonthDay md = MonthDay.from( odt );
    

    You can generate a String in your desired format.

    DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd.MM" );
    String output = md.format( f );
    

提交回复
热议问题