java 时间转为毫秒数,在Java中将日期转换为毫秒

I need to convert a Date to its corresponding Milliseconds format.I am using getTime() method of Date class in Java for this. But the milliseond generated is not of my actual date. It is one day less than my date. For eg,

I have 22-Nov-2014. If I convert this date to milliseconds format then 1,416,594,600,000 is generated. Actually this value corresponds to 21-Nov-2014.

Please help me to get an exact milliseconds value corresponds to a Date in java.

解决方案

1416594600000 corresponds to 2014-11-21T18:30:00Z. In other words, 6.30pm on November 21st 2014 in UTC. Epoch Converter is a great resource for checking things like that.

Now, a Date object doesn't have any time zone information itself. It just represents a point in time. It sounds like your "22-Nov-2014" value was probably midnight in the local time zone (India?). If you are generating values from lots of different time zones and you don't store which time zone goes with which value, you've essentially lost some information here.

If you're trying to just represent a date (rather than a point in time) but you have to store it as a milliseconds-since-the-unix-epoch value, it probably makes sense to store midnight of that date in UTC, although you should also make it very clear that that's what you're doing. If you can, you should store the value in some way that makes it more obvious it's a date - such as using a DATE field in a database. Date and time work is often really not as hard as we fear it to be if you know exactly what data you're modelling, and make that very clear everywhere in your code.

One way to make things clearer is to use a good date/time API which allows you to represent more kinds of data than java.util.Date and java.util.Calendar do. Joda Time is good for this, and Java 8 has the new java.time.* API. I'd strongly advise you to move to one of those as soon as possible.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值