Convert string to date then format the date

后端 未结 8 487
我寻月下人不归
我寻月下人不归 2020-12-03 07:52

I am formatting a string to a date using the code

String start_dt = \'2011-01-01\';

DateFormat formatter = new SimpleDateFormat(\"YYYY-MM-DD\"); 
Date date          


        
8条回答
  •  时光说笑
    2020-12-03 08:19

    tl;dr

    LocalDate.parse( "2011-01-01" )
             .format( DateTimeFormatter.ofPattern( "MM-dd-uuuu" ) ) 
    

    java.time

    The other Answers are now outdated. The troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes.

    ISO 8601

    The input string 2011-01-01 happens to comply with the ISO 8601 standard formats for date-time text. The java.time classes use these standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.

    LocalDate

    The LocalDate class represents a date-only value without time-of-day and without time zone.

    LocalDate ld = LocalDate.parse( "2011-01-01" ) ;
    

    Generate a String in the same format by calling toString.

    String output = ld.toString() ;
    

    2011-01-01

    DateTimeFormatter

    To parse/generate other formats, use a DateTimeFormatter.

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

    01-01-2011


    About java.time

    The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

    The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

    To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

    Where to obtain the java.time classes?

    • Java SE 8, Java SE 9, and later
      • Built-in.
      • Part of the standard Java API with a bundled implementation.
      • Java 9 adds some minor features and fixes.
    • Java SE 6 and Java SE 7
      • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
    • Android
      • The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
      • See How to use ThreeTenABP….

    The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

提交回复
热议问题