How to convert GMT datetime SQL data type to JAVA EST timestamp on JDK 1.7

438 Views Asked by At

datetime datatype in GMT SQL server: Column name = PostedDateTime Value = 2019-09-30 17:46:04.600

I'm trying to use JAVA code to convert that datetime value to an EST timestamp So the output should be: 2019-09-30 13:46:04

Any ideas how to convert this, please include the package that needs to be imported?

So far I have this:

SimpleDateFormat dr = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
SimpleDateFormat dr1 = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
String dateString = obj.getStringProperty("S_DISCUSSION_POSTEDDATETIME");
Date date = dr.parse(dateString);           
strRetBuffer.append(obj.getStringProperty("S_DISCUSSION_AUTHOR") + ": " + dr1.format(date) + ": " + obj.getStringProperty("S_DISCUSSION_TOPICNAME")+": " +obj.getStringProperty("S_DISCUSSION_BODY") + "\n\r" );
2

There are 2 best solutions below

0
Eric Hartojo On BEST ANSWER
        String x = "2019-09-30 17:46:04.600";
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
        Date date = formatter.parse(x);
        System.out.println(date);
        System.out.println(formatter.format(date));
        outputFormat.setTimeZone(TimeZone.getTimeZone("America/New_York"));
        System.out.println(outputFormat.format(date));
3
Ryuzaki L On

First parse the input string into LocalDateTime using DateTimeFormatter

String date = "2019-09-30 17:46:04.600";

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");

DateTimeFormatter outputFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

LocalDateTime local = LocalDateTime.parse(date, formatter);

And then convert LocalDateTime to ZonedDateTime with time zone GMT which is UTC+0

ZonedDateTime zone = ZonedDateTime.of(local, ZoneId.of("UTC"));

Finally convert the ZonedDateTime to LocalDateTime with US/Eastern and output format

String output = zone.withZoneSameInstant(ZoneId.of("US/Eastern")).toLocalDateTime().format(outputFormat);