Home > Software design >  How to convert a String contains timestamp with offset
How to convert a String contains timestamp with offset

Time:02-17

I have a String contains date and time like below : String test = ""20220215160000Z-0400";

The correct value that I need to print out is : Date = 02/15/2022 Time = 12:00

The time is basically the 16:00 - 4 hours in the offset. I couldn't figure out how to do it. Any helps will be appreciated. Currently, my codes is like below :

DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss'Z'");
Date parsedDate = dateFormat.parse(test);
Timestamp timeStamp = new Timestamp(parsedDate.getTime());
System.out.println(timeStamp.toString());

And the print out is : 2022-02-15 16:00:00.0

I need the value to be 2022-02-15 12:00:00.0

CodePudding user response:

using java.time api(you can change it to java easily):

var str = "20220215160000Z-0400"
var formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss'Z'Z")
var zonedDate = ZonedDateTime.parse(str, formatter)
println(zonedDate.offset)
var offsetTime = zonedDate.toOffsetDateTime().withOffsetSameInstant(ZoneOffset.of("-0800"))
var for2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
println(for2.format(offsetTime))

notice i'm using ZoneOffset.of("-0800") instead of ZoneOffset.of("-0000")

CodePudding user response:

Your date format is quite strange: as it does not reflect local time but UTC time, "20220215160000Z-0400" is normally regarded as local time (UTC-4) = 1600 HRS, but based on your explanation you'd like it such that UTC time = 1600 HRS, and therefore local time is 1200 HRS.

This means you need to have a "fix" on the date. See the sample code below:

        String test = "20220215160000Z-0400";
        ZoneId desiredZone = ZoneOffset.of("-0400");
        
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss'Z'Z");
        LocalDateTime localDateTime = LocalDateTime.parse(test, formatter);
        ZonedDateTime min4HrsZonedDateTime = ZonedDateTime.of(localDateTime, desiredZone);
        ZonedDateTime min4HrsZonedDateTimeFix = min4HrsZonedDateTime.withZoneSameLocal(ZoneOffset.UTC).withZoneSameInstant(desiredZone);

        System.out.println("timestamp = "  Timestamp.from(min4HrsZonedDateTimeFix.withZoneSameLocal(ZoneOffset.systemDefault()).toInstant()));

I converted the time back to UTC but without using timezone, hence the min4HrsZonedDateTimeFix

  • Related