I have an application that runs the old version of the spring application. The application has the function to create date objects using Date.parse as follows
Date getCstTimeZoneDateNow() {
String dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
def zonedDateString = new Date().format(dateFormat, TimeZone.getTimeZone('CST'))
Date date = Date.parse(dateFormat, zonedDateString)
return date // Tue Oct 18 20:36:12 EDT 2022 (in Date)
}
However, the code above is deprecated. I need to produce the same result.
I read other posts and it seems like Calender
or SimpleDateFormatter
is preferred.
And I thought SimpleDateFormatter
has more capabilities.
This post helped me understand more about what is going on in the following code SimpleDateFormat parse loses timezone
Date getCstTimeZoneDateNow() {
Date now = new Date()
String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
SimpleDateFormat sdf = new SimpleDateFormat()
sdf.setTimeZone(TimeZone.getTimeZone('CST'))
// cstDateTime prints times in cst
String cstDateTime = sdf.format(now) // 2022-10-18T20:36:12.088Z (in String)
// JVM current time
Date date = sdf.parse(cstDateTime) // Tue Oct 18 21:36:12 EDT 2022 (in Date)
return date
}
Here my goal is to return the date object that is in the format of Tue Oct 18 20:36:12 EDT 2022
The format is good. However, like the post says, when I do sdf.parse()
, it prints in JVM time.
This means, the format is good but the time zone is off.
How can I get the exact same result as before?
It does not have to use SimpleDateFormatter
. Could be anything.
Thank you so much for reading and for your time.
CodePudding user response:
Perhaps the line where you assign the format with the time-zone should be changed to make it work:
sdf.setTimeZone(TimeZone.getTimeZone('CST'))
Also the pattern seems to be obsolete, as I can't see it is used anywhere.
Try to check the output before returning 'date':
printf("cstData2: %s%n", sdf.format(date))
CodePudding user response:
Perhaps it is a logical error. It depends on the date, which time-difference is currently seen.
In this example, I try to demonstrate my output when the JVM timezone is EDT, for me, this output looks reasonable:
Date now = new Date()
printf("date: %s%n", now);
SimpleDateFormat sdf = new SimpleDateFormat()
sdf.setTimeZone(TimeZone.getTimeZone('CST'))
String formatted = sdf.format(now)
printf("formatted: %s%n", formatted)
Date date = sdf.parse(formatted)
String parsed = sdf.format(date)
printf("parsed: %s%n", parsed)
printf("date: %s%n", date);
return date
Output:
date: Thu Oct 20 02:27:53 EDT 2022
formatted: 10/20/22 1:27 AM
parsed: 10/20/22 1:27 AM
date: Thu Oct 20 02:27:00 EDT 2022
Hint: This are the actual resolved offsets for CST and EDT:
printf("offset EDT %s%n", TimeZone.default.getOffset(new Date().time)/(60*60*1000))
printf("offset CST %s%n", TimeZone.getTimeZone('CST').getOffset(new Date().time)/(60*60*1000))
Output:
offset EDT -4
offset CST -5