1

I am trying to convert date to string but the year 2018 gets changed to 2019 while conversion.

I tried with different dates, it works. It only fails for December 30 and December 31 2018.

SimpleDateFormat fmt = new SimpleDateFormat("YYYY-MM-dd");
Date date = fmt.parse("2018-12-30");
String date2 = fmt.format(date);

Expected result: 2018-12-30

Actual result: 2019-12-30

Dookoto_Sea
  • 521
  • 1
  • 5
  • 16
  • What is `sdf`?? – Andronicus Aug 23 '19 at 05:00
  • `fmt` seems to work just fine, produces a `Date` of `Sun Dec 30 00:00:00 AEDT 2018`. What is `sdf` setup as? Also, you really should be using the `java.time` API instead of these out-of-date classes – MadProgrammer Aug 23 '19 at 05:02
  • I just updated the sdf declaration – Dookoto_Sea Aug 23 '19 at 05:14
  • 1
    Related: https://stackoverflow.com/questions/15133549/difference-between-yyyy-and-yyyy-in-nsdateformatter. If you google for "SimpleDateFormat YYYY vs yyyy", then you'll find several links, which say: "Don't use YYYY". –  Aug 23 '19 at 05:27
  • I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalDate` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Aug 23 '19 at 13:01

3 Answers3

8

Case-sensitive

Uppercase YYYY means year of a week-based year rather than a calendar year (lowercase yyyy).

So you are seeing a feature, not a bug. The second to the last day of 2018 is in the first week of 2019 according to the definition of a week used by SimpleDateFormat. That definition varies by Locale.

Avoid legacy date-time classes

You are using terrible date-time classes that were supplanted years ago by the modern java.time classes defined in JSR 310.

LocalDate

The LocalDate class is appropriate to your string inputs.

String input = "2019-12-30" ;
LocalDate ld = LocalDate.parse( input ) ;
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
1

Where sdf is setup?? Just use fmt it will works fine. Try Following.

SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
Date date = fmt.parse("2018-12-30");
String date2 = fmt .format(date);
IsharaD
  • 322
  • 2
  • 4
  • 17
1

You don't need to format the date again with SimpleDateFormat. Just use as follows.

Date format required : 2019-12-30

The appropriate date format specified will be : yyyy.MM.dd (yyyy : Represents full year)

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = simpleDateFormat.parse("2018-12-30");
String sDate = simpleDateFormat.format(date);
Hasitha Jayawardana
  • 2,326
  • 4
  • 18
  • 36