How to get time from user with respect to timezone

烂漫一生 提交于 2019-12-13 09:38:11

问题


Good day,

I am working on a project reporting.

and its my first time i have to deal with datetime.

I have database mongodb, as we know mongodb stores date time in UTC.

now i would like to show data from users provided date and time zone.

for example if i am login in my system i can set my timezone from dropdown. say i choose GMT+05:00 now if i choose date start and end as 2018-07-05 and 2018-07-06

how can i get the proper time with user specified time zone.

I guess if user has selected the time zone GMT+05:00 then date must be start from 2018-07-04 19:00:00 and 2018-07-05 19:00:00 minus 5 hours from given time.

how can i achieve this is java.


回答1:


    String userTimeZone = "Asia/Samarkand";
    String userDate = "2018-07-05";

    ZoneId zone = ZoneId.of(userTimeZone);
    Instant dbInstant = LocalDate.parse(userDate)
            .atStartOfDay(zone)
            .toInstant();

    System.out.println(dbInstant);

This prints what you had expected:

2018-07-04T19:00:00Z

I don’t know MongoDB’s JDBC driver, but I assume it would be happy to accept an Instant and store it in UTC in the database.

GMT+05:00 is not really a time zone, it’s a GMT offset. If your user is in a time zone that uses the same UTC offset always, it would work. But politicians tend to change their minds, so even if that time zone doesn’t use summer time (DST), it may do in a couple of years. And very many time zones already do. Therefore your user should pick a proper time zone like Asia/Tashkent, for example.

Edit: I understand from your comment that MongoDB expects a java.util.Date object. Funny and old-fashioned, but in that case the conversion is straightforward when you know how:

    Date dbDate = Date.from(dbInstant);
    System.out.println(dbDate);

On my computer in Europe/Copenhagen time zone this printed:

Wed Jul 04 21:00:00 CEST 2018

Don’t be fooled: this is the correct time. Date.toString (implicitly called through System.out.println) grabs my JVM’s time zone setting and uses it for generating the string. The Date itself doesn’t have a time zone in it and holds the same point in time as the Instant.

Link: Oracle tutorial: Date Time




回答2:


If you already have the user selected time zone what you need to do is parse the date from DB to GMT:

Date dateFromDb = getDateFromDb(); // date from db
LocalDateTime localDateTime = LocalDateTime.ofInstant(new Date().toInstant(), ZoneId.of("GMT")); // parsing date to GMT but using LocalDateTime
Date correctDate = Date.from(localDateTime); // transforming into java.util.Date


来源:https://stackoverflow.com/questions/50052157/how-to-get-time-from-user-with-respect-to-timezone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!