codereviewanskquestions
codereviewanskquestions

Reputation: 13998

Java 8 LocalDateTime to Date Lost Timezone

I have this code and my system's default timezone is PDT. After the timezone conversion, finalDate shows time in PDT. How do I make it show the finalDate in "Asia/Singapore"?

String strDate = 201507081245;
DateTimeFormatter mx3DateFormat = DateTimeFormatter.ofPattern("yyyyMMddHHmm");
LocalDateTime localDateTime = LocalDateTime.parse(strDate, format);
Instant instant = localDateTime.atZone(ZoneId.of("Asia/Singapore")).toInstant();
Date finalDate = Date.from(instant);

Upvotes: 2

Views: 987

Answers (1)

Codebender
Codebender

Reputation: 14471

A java.util.Date object is not specific to a particular time zone. Yet its toString method applies your JVM’s current default time zone.

You can ask it to print the time in a particular timezone with a DateFormat such as SimpleDateFormat.

Something like,

    SimpleDateFormat dateFormat = new SimpleDateFormat("hhhhMMddHHmm");
    dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Singapore"));
    System.out.println(dateFormat.format(finalDate));

Upvotes: 4

Related Questions