Archana
Archana

Reputation: 53

Java time zone format issue

The saved time in the application is in UTC. The users of the application are in different timezones, such as PST, IST etc.

My issue is very similar to the one in this post. I tried implementing a solution provided there, but it does not seem to be working for me:

Calendar calendar = Calendar.getInstance();
calendar.setTime(history.getCreatedTimestamp());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

//Here you say to java the initial timezone. This is the secret
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
//Will print in UTC
System.out.println(sdf.format(calendar.getTime()));

//Here you set to your timezone
sdf.setTimeZone(TimeZone.getDefault());
//Will print on your default Timezone
System.out.println(sdf.format(calendar.getTime()));

Upvotes: 1

Views: 143

Answers (1)

user9386716
user9386716

Reputation: 33

I suggest you to use Java 8 classes (SimpleDateFormat and Calendar are trouble, avoid them if possible):

long timestamp = history.getCreatedTimestamp();
// create Instant from timestamp value
Instant instant = Instant.ofEpochMilli(timestamp);

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

// convert to UTC
System.out.println(formatter.format(instant.atZone(ZoneOffset.UTC)));

// convert to another timezone
System.out.println(formatter.format(instant.atZone(ZoneId.of("America/Los_Angeles"))));

// convert to JVM default timezone
System.out.println(formatter.format(instant.atZone(ZoneId.systemDefault())));

Unfortunately, short zone names like PST and IST are ambiguous (check this list), so you need to translate them to IANA's names (which are the standard used by Java, such as America/Los_Angeles or Europe/London).

More about timezones: https://codeofmatt.com/2015/02/07/what-is-a-time-zone

Upvotes: 3

Related Questions