DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ddMMyy", Locale.US);
LocalDate d = LocalDate.parse("280218", formatter);
String dToString = d.toString();
System.out.println(dToString);
LocalDate parsedBack = LocalDate.parse(dToString);
System.out.println(parsedBack);
Prints (two identical lines):
2018-02-28
2018-02-28
The result will be the same on all devices.
I’m not sure exactly why you are doing what you are doing, so I may not have hit exactly what you are after. I have tried to mimic your code as closely as possible only using java.time
instead of the long outdated Date
and SimpleDateFormat
classes. It goes a lot more smoothly. java.time
is the modern Java date and time API and is generally much nicer to work with.
Since a LocalDate
is a date without time of day or time zone, your issue with the time zone differences is eliminated from the outset. LocalDate.toString()
always gives the same string on all devices. And as a further plus, LocalDate
parses the same string back without an explicit formatter. It could hardly be easier.
If your Android level is not high enough to use java.time
natively, add ThreeTenABP to your project and make sure to import org.threeten.bp.LocalDate
and org.threeten.bp.format.DateTimeFormatter
.
What went wrong in your code?
The time zone that Date.toString()
uses for generating the string hasn’t got anything to do with the formatter you used for parsing the date. Though not officially documented, the method uses the JVM’s time zone setting. I cannot guarantee it will work on your devices, but at least on my Mac I can control the result of Date.toString()
through either
System.setProperty("user.timezone", "Asia/Kolkata");
or
System.setProperty("user.timezone", "GMT+05:30");
This way I can get the results you got from your different devices. The three and four letter time zone abbreviations are ambiguous and often not true time zones, though, so don’t rely on them for parsing the string from Date.toString()
back. BTW TimeZone.setDefault()
has the same effect and may be considered more high-level; it’s just me having made a habit of avoiding the outdated date-time classes including TimeZone
.
Links