Search code examples
javadatetimeutcdatetimeformatter

IST to UTC conversion in java


I am trying to convert the date time string received (IST format) to the UTC format.

String time = 124200;
String date = 05/09/21;
DateTimeFormatter parser = DateTimeFormatter.ofPattern("dd/MM/yyHHmmss").withZone(ZoneId.of("UTC")); 
String dateInString = date.concat(time);
ZonedDateTime dateTime = ZonedDateTime.parse(dateInString, parser);
return Timestamp.valueOf(dateTime.toLocalDateTime()).toString();

This code snippet does not convert to UTC. Please let me know what is the issue


Solution

  • Long story short: Your parsed time is regarded as UTC because you attached the ZoneId.of("UTC") first. That means you take that time of day at that very date as if it was recorded in UTC.

    Instead, you should have used IST as the original zone:

    public static void main(String[] args) {
        // time and date in IST (?)
        String time = "124200";
        String date = "05/09/21";
        // two parsers, one for date and one for time
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM/uu");
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HHmmss");
        // parse the date and time using the parsers
        LocalDate localDate = LocalDate.parse(date, dateFormatter);
        LocalTime localTime = LocalTime.parse(time, timeFormatter);
        
        /*
         * until here, there's just date and time, NO zone!
         * If you apply UTC here, the parsed date and time would be regarded as UTC!
         */
        
        // create a ZonedDateTime with the desired SOURCE zone from the date and time
        ZonedDateTime istTime = ZonedDateTime.of(localDate, localTime, ZoneId.of("Asia/Kolkata"));
        // then convert it to UTC
        ZonedDateTime utcTime = istTime.withZoneSameInstant(ZoneId.of("UTC"));
        // print the results in order to view the difference
        System.out.println(istTime);
        System.out.println(utcTime);
    }
    

    The output of this code snippet (implicit use of ZonedDateTime.toString()) is

    2021-09-05T12:42+05:30[Asia/Kolkata]
    2021-09-05T07:12Z[UTC]
    

    If your system has IST as its default zone, you can write ZoneId.systemDefault() instead of ZoneId.of("Asia/Kolkata"), but I had to use the explicit zone on my machine, I'm in Europe.