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)
YearMonth.parse(
"12/2016" ,
DateTimeFormatter.ofPattern( "MM/uuuu" ) )
)
.atDay( 1 )
.format( DateTimeFormatter.ofPattern( "MM/dd/uuuu" ) ) // 12/01/2016
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();
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?
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.