-1

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?

guest
  • 128
  • 3
  • 4
    Possible duplicate of [Java string to date conversion](https://stackoverflow.com/questions/4216745/java-string-to-date-conversion) – Mark Melgo Feb 20 '19 at 07:17
  • Is that your only requirement? If yes, cut the last three characters? No, seriously, have a look at `java.time`, especially `LocalDate`, `LocalTime` and `LocalDateTime`. – deHaar Feb 20 '19 at 07:17
  • 1
    Did you mean "year and month" in that last line? "year and date" (as in day-of-month) makes no sense. – Basil Bourque Feb 20 '19 at 07:21
  • What does this have to do with databases and SQLite? Delete extraneous tags. – Basil Bourque Feb 20 '19 at 07:27
  • So `2019-09-29` should become `2019-29`? For what purpose if I may be curious? Or did you mean that the day of the year should come after the hyphen, so `2019-272`? – Ole V.V. Feb 20 '19 at 10:27

2 Answers2

4

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);
}
guest
  • 128
  • 3
2

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

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154