how to convert localdatetime into GMT?

Viewed 562

i have string date like this

2020-05-19 10:46:09 this is Asia/Jakarta time

i want to convert become GMT and here my code

String created = New_tradingHistory_trade.getCreated_at();
                    Date date1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(created);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
                    String CreatedGMT = sdf.format(date1);
                    System.out.print(CreatedGMT);

what i got always like 2020-05-19 10:46:09 2020-05-19 10:46:09 my question is how to convert my date to GMT ?

1 Answers

you should use the java-8 date time api and stop using legacy Date and SimpleDateFormat

  1. The input string you have is in local date time
  2. So parse it into LocalDateTime using DateTimeFormatter
  3. Then convert localDateTime into ZoneDateTime at zone Asia/Jakarta
  4. Finally convert zoneDateTime into GTM date time which is equal to UTC

String input = "2020-05-19 10:46:09";

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

LocalDateTime localDateTime = LocalDateTime.parse(input,formatter);

ZonedDateTime zoneDateTime = localDateTime.atZone(ZoneId.of("Asia/Jakarta"));

System.out.println(zoneDateTime);

ZonedDateTime gmtDateTime = zoneDateTime.withZoneSameInstant(ZoneOffset.UTC);

System.out.println(gmtDateTime);
Related