How to convert date from MM/YYYY to MM/DD/YYYY in Java

后端 未结 4 1206
名媛妹妹
名媛妹妹 2021-01-25 03:55

I want to convert date from MM/YYYY to MM/DD/YYYY, how i can do this using SimpleDateFormat in Java? (Note: DD can be start date of that month)

4条回答
  •  北海茫月
    2021-01-25 04:30

    tl;dr

    YearMonth.parse( 
        "12/2016" , 
        DateTimeFormatter.ofPattern( "MM/uuuu" ) )
    )
    .atDay( 1 )
    .format( DateTimeFormatter.ofPattern( "MM/dd/uuuu" ) )  // 12/01/2016
    

    java.time

    Java now includes the YearMonth class to represent exactly this kind of value, a month and a year without a day-of-month.

    The default format for parsing/generating strings of a month-year is YYYY-MM. That format is defined as part of the ISO 8601 format. The java.time classes use ISO 8601 formats by default.

    Your input string has alternate format so we must specify a formatting pattern.

    String input = "12/2016" ;  // December 2016.
    DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/uuuu" );
    YearMonth ym = YearMonth.parse( input , f );
    

    See the results by calling toString.

    String output = ym.toString();
    

    2016-12

    Specify a day-of-month to create a LocalDate instance. The LocalDate class represents a date-only value without time-of-day and without time zone.

    LocalDate ld = ym.atDay( 1 );
    

    You can let the class figure out the last day of the month. Remember that February varies in length for Leap Year. The YearMonth class knows how to handle Leap Year.

    LocalDate ld = ym.atEndOfMonth();
    

    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 and 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 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.

    FYI, Java has a similar class, MonthDay.

提交回复
热议问题