Java.util.date获取客户端时区的实际日期 [英] Java.util.date get the actual date at client timezone

查看:253
本文介绍了Java.util.date获取客户端时区的实际日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

上下左右搜索-找不到该问题的简单答案:

Searching up and down, right and left - don't find simple answer to this question:

我有java.util.Date实例,该实例从mySQL获取其值.

I have java.util.Date instance, which get its value from mySQL.

我也有登录用户的时区代码.

Also I have time-zone code of the logged-in user.

我需要获取用户时区的实际时间.

I need to get the actual time at user time-zone.

例如:

我的服务器计算机时区是GMT + 2.

My server-machine time-zone is GMT+2.

我在 DB 中的日期值为:2017-02-09 16:38:58.000

My date value in DB is: 2017-02-09 16:38:58.000

根据我的服务器机器时区,我将其放入日期实例中:2017-02-09T16:38:58.000 + 0200

According to my server-machine-time-zone I get it into date instance as: 2017-02-09T16:38:58.000+0200

现在,我需要知道如何处理:

Now I need to know what to do if:

以防万一,例如,我的客户时区代码是GMT + 4,我想获取:

In case, for sample, my client-time-zone-code is GMT+4, I want to get:

2017-02-09 20:38:58.000

2017-02-09 20:38:58.000

纯正的日期,即我所在的时区,并且不包含"+4"或"GMT"指示.

Pure date, that is right to my time zone and not contain "+4" or "GMT" indication.

简而言之:将我的java.util.date转换为可以转换为特定时区的纯日期.

In short words: convert my java.util.date to pure date that right to specific time-zone.

听起来很简单?在阅读了很多文献之后,我已经不确定这真的很简单.

Sound very simple? after read very much documentaion, I already not sure that this is really simple.

推荐答案

java.util.Date不存储任何时区.它仅存储自"epoch"(即1970年1月1日,UTC时间00:00:00)以来的毫秒数.

java.util.Date does not store any time zone. It just stores the number of milliseconds since the 'epoch', which is 1 January 1970, 00:00:00 UTC.

因此,您要做的就是知道服务器计算机的时区,找到该时区和要将其转换为时区之间的时间段,并增加或减少该时间段.

Thus, all you have to do is to know the time zone of your server machine, find the period between this time zone and the time zone you want to convert it to and add or subtract the period.

更新:

int clientGMT = 4; //GMT you want to convert to
int serverGMT = 2; //server's GMT
int delta = clientGMT - serverGMT; //delta between the dates

//assume this is the date in GMT + 2 received from the server
Date d1 = new SimpleDateFormat("dd.MM.yyyy hh:mm:ss").parse("12.03.2019 13:00:00");

//... and you want to convert it to GMT + 4 (client side's time zone)
Date resultDate = new Date(d1.getTime() + delta * 3600000);

P.S.是的,您必须手动操作时区,正如我上文所述,java.util.Date不会存储此信息(每个日期均假定为UTC).

P.S. Yes, you have to manipulate time zones manually, as I said above, java.util.Date does not store this information (each date is assumed to be in UTC).

这篇关于Java.util.date获取客户端时区的实际日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆