Saving Date Time For All Time Zones In Java
Solution 1:
Store into your database the difference, measured in milliseconds, between the current time and the epoch of midnight, January 1, 1970 UTC. that you can get by calling System.currentTimeMillis()
.
Once you have it you can provide the time in any Time Zone that you want, here is a simple code snippet that shows the time in all the time zones available on my machine.
This code uses the java.time framework built into Java 8 and later. Much of this functionality has also been back-ported to Java 6 & 7 and to Android.
longtime= System.currentTimeMillis();
Instantinstant= Instant.ofEpochMilli(time);
ZoneId.getAvailableZoneIds().stream().forEach(id -> {
ZoneIdzId= ZoneId.of(id);
LocalDateTimelocalDateTime= LocalDateTime.ofInstant(instant, zId);
System.out.printf(
"The current time in %s is %s%n",
zId, localDateTime.format(DateTimeFormatter.ISO_DATE_TIME)
);
}
);
Here is the equivalent for older versions of Java:
longtime= System.currentTimeMillis();
Calendarcal= Calendar.getInstance();
cal.setTimeInMillis(time);
for (String id : TimeZone.getAvailableIDs()) {
SimpleDateFormatformatter=newSimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
formatter.setTimeZone(TimeZone.getTimeZone(id));
System.out.printf(
"The current time in %s is %s%n", id, formatter.format(cal.getTime())
);
}
Response Update:
As you want to keep the original TimeZone
, you will also have to store the time zone Id into your database in the pseudo standard format GMT+/-mm:ss.
For this, first you need to get the delta compared to UTC time (in the code snippet below tz
is my current TimeZone):
int offsetFromUTC = tz.getOffset(time);
Then from this you can convert this delta in milliseconds into the expected time zone id which can be done like this:
String timeZoneId = String.format(
"GMT%+02d:%02d", offsetFromUTC / (60 * 60 * 1000), offsetFromUTC / (60 * 1000) % 60
);
The value of timeZoneId
is the second value that you have to store into the database. With these two values you can display the time in any expected format, for example:
Calendarcal= Calendar.getInstance();
// Here I use the time retrieved from the DB
cal.setTimeInMillis(time);
SimpleDateFormatformatter=newSimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
// Here I use the time zone id retrieved from the DBTimeZonetz= TimeZone.getTimeZone(timeZoneId);
formatter.setTimeZone(tz);
System.out.printf("The current time in %s is %s%n", id, formatter.format(cal.getTime()));
Solution 2:
So how can i save date time so it would be same for all time zones
You should use UTC to store your dates, so if someone is using your app in +1 timezone, you need to convert it to UTC first. Timezone should only be used to display the time to the users.
Post a Comment for "Saving Date Time For All Time Zones In Java"