0

I have string timestamp like 2020-05-25 08:03:24

I have tried to split the String using " " (a whitespace) as delimiter to get two Strings "2020-05-25" and "08:03:24". After that, I used substring to get the hours and added 7 to have jakarta time.
But when it is 17:01:00 for example, my calculated date is wrong.
The date given is in UTC.

I want to convert it become timezone [ASIA/Jakarta] how to convert utc timestamp become asia jakarta time?

deHaar
  • 17,687
  • 10
  • 38
  • 51
yuyu kungkung
  • 137
  • 2
  • 13

1 Answers1

4

You can use java.time if you are using Java 8 or higher.

The library provides handy possibilities of converting datetimes that don't have information about a time zone (like your example String) to a zone and handle conversions from one zone to another.

See this example:

public static void main(String[] args) {
    // datetime string without a time zone or offset
    String utcTimestamp = "2020-05-25 08:03:24";
    // parse the datetime as it is to an object that only knows date and time (no zone)
    LocalDateTime datetimeWithoutZone = LocalDateTime.parse(utcTimestamp,
                                    DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    // convert it to a zone-aware datetime object by adding a zone
    ZonedDateTime utcZdt = datetimeWithoutZone.atZone(ZoneId.of("UTC"));
    // print the datetime in utc once
    System.out.println(utcZdt);
    // then convert the zoned datetime to a different time zone
    ZonedDateTime asiaJakartaZdt = utcZdt.withZoneSameInstant(ZoneId.of("Asia/Jakarta"));
    // and print the result
    System.out.println(asiaJakartaZdt);
}

The output is

2020-05-25T08:03:24Z[UTC]
2020-05-25T15:03:24+07:00[Asia/Jakarta]
deHaar
  • 17,687
  • 10
  • 38
  • 51