How to Convert String date format example I have Date like this
2019-01-01
and change the format into
2019-01
the year and date only?
How to Convert String date format example I have Date like this
2019-01-01
and change the format into
2019-01
the year and date only?
You can use DateTimeFormatter like this :
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
String result = formatter.format(LocalDate.parse("2019-01-01"));
The result should be
2019-01
About parsing
you can use LocalDate.parse("2019-01-01") because parse use by default DateTimeFormatter.ISO_LOCAL_DATE, which is the same format of your String
public static LocalDate parse(CharSequence text) {
return parse(text, DateTimeFormatter.ISO_LOCAL_DATE);
}
YearMonth
.from(
LocalDate.parse( "2019-01-01" )
)
.toString()
2019-01
YearMonthI suppose you meant "year and month" in that last line. If so, use the YearMonth class, along with LocalDate.
First, parse the LocalDate as shown in correct Answer by guest.
LocalDate ld = LocalDate.parse( "2019-01-01" ) ;
Extract a YearMonth object to represent, well, the year and the month.
YearMonth ym = YearMonth.from( ld ) ;
Generate text representing this value in standard ISO 8601 format.
String output = ym.toString() ;
2019-01