简体   繁体   中英

Saving date time for all time zones in java

I have an application in which user creates questions and others can see date time (when the question was created) with it. Now i get the server date time and save it in db but the problem is app is used by someone who live in a country with a 6-7 hour gap. Well a small example would be that i live in some country and i create question at time 7:00pm but time in USA is 11am (just a guess). So user immediately retrieves question but for him question time should be 11am and not 7pm. So how can i save date time so it would be same for all time zones . I m kinda confused so i need a little help . I know it's related to UTC date time but can someone elaborate this a bit more :) . Thank u

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.

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 .

long time = System.currentTimeMillis();
Instant instant = Instant.ofEpochMilli(time);
ZoneId.getAvailableZoneIds().stream().forEach(id -> {
        ZoneId zId = ZoneId.of(id);
        LocalDateTime localDateTime = 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:

long time = System.currentTimeMillis();
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(time);
for (String id : TimeZone.getAvailableIDs()) {
    SimpleDateFormat formatter = new SimpleDateFormat("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:

Calendar cal = Calendar.getInstance();
// Here I use the time retrieved from the DB
cal.setTimeInMillis(time);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
// Here I use the time zone id retrieved from the DB
TimeZone tz = TimeZone.getTimeZone(timeZoneId);
formatter.setTimeZone(tz);
System.out.printf("The current time in %s is %s%n",  id, formatter.format(cal.getTime()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM