Samarland
Samarland

Reputation: 581

Set timeZone in Date Java

Trying to set the timeZone in Date( I know Date is deprecated)

    LOG.error(modifiedDate + "Date in service"); //Mon Sep 21 06:15:00 CDT 2020
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z", Locale.ENGLISH);
format.setTimeZone(TimeZone.getDefault());
String dateString = format.format(modifiedDate);
LOG.error(dateString + "  dateString"); //2020-09-21 06:15:00 -0500
Date date = format.parse(dateString);
LOG.error(date + "    date after parsing"); //Mon Sep 21 06:15:00 CDT 

timeZone isn't changing after the parse, what am I missing?

Upvotes: 0

Views: 191

Answers (1)

rzwitserloot
rzwitserloot

Reputation: 103823

A java.util.Date object is lying. It's not a date. It is a moment in time, and it has no timezone information. It's just a wrapper around millis-since-epoch. It physically doesn't have the neccessary fields to store that.

(let's stop calling an instance of j.u.Date a 'date', because it just isn't one. You might as well call all instances of Integer a 'string', and all files 'a Grandma', about as sane). Let's call them by their right name: "crappy instant".

What you've done is set the timezone of the formatter object. This is working as intended: When you format this crappy instant object with your formatter-with-timezone-info-attached, you get the 'instant in time', translated to human-consumable form, with timezone info, adjusted for that timezone.

Then you ask to parse it back in but that's an issue: that's a very broad job; 'parse this bunch of characters into a "crappy instant"'.

In this case, the bag o' chars you've given includes timezone info already so that will be used. Remember, Date objects are crappy instants - they contain no timezone!!

Which should then raise some eyebrows - as last act you log date, which effectively logs the result of invoking the toString() method on your crappy instant instance. This will.... create a formatter with the system default timezone and use that to render it in human form, but make no mistake, that is NOT actually what is stored in that crappy instant object you have. All that is stored in there is 1600686900000. That's it.

I strongly suggest you follow deHaar's comment: No, you don't want crappy instant. If you have a value handed to you of type crappy instant (java.util.Date), convert it to Instant immediately.

If you must hand off a calculated time value back to some method or interface or field or whatnot and must be in date form, convert your nice instant instance (java.time.Instant) back to a crappy instant form.

Upvotes: 6

Related Questions