如何从用户那里获取关于时区的时间

如何从用户那里获取关于时区的时间

问题描述:

美好的一天,

我正在做一个项目报告.

I am working on a project reporting.

这是我第一次处理日期时间.

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

我有数据库 mongodb,因为我们知道 mongodb 以 UTC 存储日期时间.

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.

例如,如果我在我的系统中登录,我可以从下拉菜单中设置我的时区.如果我选择日期开始和结束时间为 2018-07-05 和 2018-07-06,我现在选择 GMT+05:00

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.

我想如果用户选择了时区 GMT+05:00 那么日期必须从 2018-07-04 19:00:00 和 2018-07-05 19:00:00 开始减去给定时间的 5 小时.

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.

我如何实现这是java.

how can i achieve this is java.

    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

2018-07-04T19:00:00Z

我不知道 MongoDB 的 JDBC 驱动程序,但我认为它会很乐意接受 Instant 并将其以 UTC 格式存储在数据库中.

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 并不是真正的时区,而是 GMT 偏移量.如果您的用户所在的时区始终使用相同的 UTC 偏移量,则它会起作用.但政客们往往会改变主意,因此即使该时区不使用夏令时 (DST),也可能在几年后使用.很多时区已经这样做了.因此,您的用户应该选择一个合适的时区,例如 Asia/Tashkent.

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.

我从您的评论中了解到 MongoDB 需要一个 java.util.Date 对象.有趣和老式,但在这种情况下,如果您知道如何转换,则转换很简单:

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:

2018 年 7 月 4 日星期三 21:00:00 CEST

Wed Jul 04 21:00:00 CEST 2018

不要上当:现在是正确的时间.Date.toString(通过 System.out.println 隐式调用)获取我的 JVM 时区设置并将其用于生成字符串.Date 本身没有时区,并且与 Instant 保持相同的时间点.

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.

链接: Oracle 教程:日期时间