ashok
ashok

Reputation: 1268

Simpledateformate timezone not converting

In java simpledateformat i am not able to convert to the timezone for IST. The input I am giving is in UTC but I want to convert to IST.

        SimpleDateFormat format1 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
        SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = format1.parse("20-01-2019 13:24:56");
        TimeZone istTimeZone = TimeZone.getTimeZone("Asia/Kolkata");
        format2.setTimeZone(istTimeZone);
        String destDate = format2.format(date);
        System.out.println(destDate); //2019-01-20 13:24:56

But it has to add +5:30 to make it IST.

Upvotes: 0

Views: 80

Answers (2)

Jens Dibbern
Jens Dibbern

Reputation: 1454

I added timezone output and explicit UTC timezone assignment to format1 to your code:

    SimpleDateFormat format1 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
    SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    System.out.println(format1.getTimeZone());
    TimeZone utcTimeZone = TimeZone.getTimeZone("UTC");
    format1.setTimeZone(utcTimeZone);
    Date date = format1.parse("20-01-2019 13:24:56");
    TimeZone istTimeZone = TimeZone.getTimeZone("Asia/Kolkata");
    format2.setTimeZone(istTimeZone);
    String destDate = format2.format(date);
    System.out.println(destDate); // 2019-01-20 13:24:56

You should see that SimpleDateFormat defaults to your local timezone. Setting UTC explicitly should work.

Upvotes: 2

xingbin
xingbin

Reputation: 28289

As said in another answer, you did not set time zone for format1. You can also use java.time package to solve this problem since java8.

Since 20-01-2019 13:24:56 does not contains time zone information, you can:

  1. parse it as LocalDateTime.
  2. convert the LocalDateTime to ZonedDateTime in UTC.
  3. get the same instant in time zone IST.

Example:

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

ZonedDateTime zonedDateTime = LocalDateTime
        .parse("20-01-2019 13:24:56", format1) // parse it without time zone
        .atZone(ZoneId.of("UTC")) // set time zone to UTC
        .withZoneSameInstant(ZoneId.of("Asia/Kolkata")); // convert UTC time to IST time

System.out.println(format2.format(zonedDateTime)); //2019-01-20 18:54:56

Upvotes: 4

Related Questions