java.util.date返回指定时间,Java.util.date获取客户端时区的实际日期

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

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.

For example:

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

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

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:

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

2017-02-09 20:38:58.000

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

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 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.

UPDATE:

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. 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).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值