I'm pulling a date string from a SQL table. The date string being pulled from Sql is...
2020-07-28 15:35:45.9375232 -05:00
and when I try and parse and format, it's returning a different time than what was passed in.
Method1:
String record = data.getValue(4, 1)
// returns "2020-07-28 15:43:16.5168174 -05:00" from SQL table
def formattedDate = Date.parse("yyyy-MM-dd HH:mm:ss.SSSSSSS XXX", record).format("yyyy-MM-dd'T'HH:mm:ss.SSS")
log.logInfo("queried date = " + formattedDate)
Returns 2020-07-28T17:09:24.174
and Method2:
def queriedDate2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSSS XXX").parse(record)
log.logInfo("queriedDate2= " + queriedDate2)
Returns Tue Jul 28 17:09:24 CDT 2020
Can anyone help me understand what's going on?
Probably SimpleDateFormat
is ignoring the zone-offset (-5 hours) in the give date-time string and applying your JVM's time-zone while parsing it. I suggest you switch from the outdated and error-prone java.util.Date
and SimpleDateFormat
to the modern date-time API to get rid of such problems.
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
// Given date-time string
String dateTimeStr = "2020-07-28 15:35:45.9375232 -05:00";
// OffsetDateTime from the given date-time string
OffsetDateTime odt = OffsetDateTime.parse(dateTimeStr,
DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSSSSSS XXX"));
System.out.println(odt);
// You can print it in different forms using DateTimeFormatter patterns e.g.
System.out.println(DateTimeFormatter.ofPattern("MMM dd uuuu").format(odt));
System.out.println(DateTimeFormatter.ofPattern("MMM dd uuuu HH:mm:ss.SSSSSSS ZZZZZ").format(odt));
System.out.println(DateTimeFormatter.ofPattern("MM/uuuu/dd hh:mm:ss a").format(odt));
}
}
Output:
2020-07-28T15:35:45.937523200-05:00
Jul 28 2020
Jul 28 2020 15:35:45.9375232 -05:00
07/2020/28 03:35:45 pm