Click here to Skip to main content
15,891,473 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have three parameters, UTCTime and two offsets all three as strings, I need to convert them as below

Input: 
    String UTCTime = "2020-09-29 16:06:00";
    String PSTOffset = "-07:00";
    String LocalOffset = "-04:00";

Output Expected:
        LocalTime = "2020-09-29 12:06:00"
        PSTTime = "2020-09-29 09:06:00"


What I have tried:

I tried doing something like this

OffsetDateTime OffsetLocalTime = OffsetDateTime.parse(String.format("%sT%sZ",UTCTime.split(" ")[0],UTCTime.split(" ")[1]));
    OffsetLocalTime = OffsetLocalTime.withOffsetSameInstant(ZoneOffset.of(LocalOffset));

    OffsetDateTime OffsetPSTTime = OffsetDateTime.parse(String.format("%sT%sZ",UTCTime.split(" ")[0],UTCTime.split(" ")[1]));
    OffsetPSTTime = OffsetPSTTime.withOffsetSameInstant(ZoneOffset.of(PSTOffset));

    String LocalTime = String.format("%s %s",OffsetLocalTime.toString().substring(0,OffsetLocalTime.toString().lastIndexOf('-')).split("T")[0],OffsetLocalTime.toString().substring(0,OffsetLocalTime.toString().lastIndexOf('-')).split("T")[1]);
    String PSTTime = String.format("%s %s",OffsetPSTTime.toString().substring(0,OffsetPSTTime.toString().lastIndexOf('-')).split("T")[0],OffsetPSTTime.toString().substring(0,OffsetPSTTime.toString().lastIndexOf('-')).split("T")[1]);

    System.out.println("OffsetLocalTime: "+OffsetLocalTime);
    System.out.println("OffsetPSTTime: "+ OffsetPSTTime);

    System.out.println("LocalTime: "+ LocalTime);
    System.out.println("PSTTime: "+ PSTTime);

    Actual Output:

    OffsetLocalTime: 2020-09-29T12:06-04:00
    OffsetPSTTime: 2020-09-29T09:06-07:00
    LocalTime: 2020-09-29 12:06
    PSTTime: 2020-09-29 09:06

I am missing out seconds and this seems to be an inefficient way beacuse i do not need 'T' or offset in my output and i am getting rid of them. I am not sure if this question is already asked. Any help is appreciated.
Posted
Updated 1-Oct-20 9:05am

1 solution

Your input string does not have any zone defined to it. In order to convert to anything, first thing is to normalize (base) it to some format (preferrable UTC) and then use the in-built conversions as per need.
Java
// Input string
String inputTime = "2020-09-29 16:06:00";

// Define the input string format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
 
// Convert it to UTC
OffsetDateTime inputTimeUTC = LocalDateTime.parse(inputTime, formatter).atOffset(ZoneOffset.UTC);
Once you have this now, you can add ffsets as per need like:
Java
// Example for -7 hours
OffsetDateTime outputTime = inputTimeUTC.withOffsetSameInstant(ZoneOffset.ofHours(-7));

Try!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900