SimpleDateFormat With Timezone Displaying Dates In My Timezone, How Do I Fix This?
Given these two date Strings, I am trying to create a menu that allows you to select from the two dates (these are returned from an API with the users timezone): 2019-12-20T00:00:0
Solution 1:
You can use the modern java.time package instead and specially ZonedDateTime
that handles time zones.
String str = "2019-12-20T00:00:00.000-05:00";
ZonedDateTime zonedDateTime = ZonedDateTime.parse(str);
And when showing it in the UI use DateTimeFormatter
to convert it to a formatted string
DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
or with some custom format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
which will give you for the 2 formats
System.out.println(formatter.format(zonedDateTime));
2019-12-20T00:00-05:00
2019-12-20 00:00
Solution 2:
SimpleDateFormat.getDateInstance(...)
will give you an instance in the JVM's default time zone.
Set the time zone to whatever you need it to be.
DateFormat dateFormat = SimpleDateFormat.getDateInstance(DateFormat.SHORT);
dateFormat.setTimeZone(/* whatever */);
return dateFormat.format(date);
Post a Comment for "SimpleDateFormat With Timezone Displaying Dates In My Timezone, How Do I Fix This?"