简体   繁体   中英

Java how to Convert String Date format

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);
}

tl;dr

YearMonth
.from(
    LocalDate.parse( "2019-01-01" )
)
.toString()

2019-01

YearMonth

I 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM