在Java中将日期转换为毫秒 [英] Convert Date to Milliseconds in Java
问题描述
我需要将日期转换为相应的毫秒格式。我正在使用 Date $ c的
类。但是生成的毫秒不是我的实际日期。比我的约会少一天。例如, getTime()
方法Java中的$ c>
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,
我有 2014年11月22日
。如果我将此日期转换为毫秒格式,则会生成 1,416,594,600,000
。实际上,该值对应于 2014年11月21日
。
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
.
请帮助我获取与Java中 Date
相对应的精确毫秒值。
Please help me to get an exact milliseconds value corresponds to a Date
in java.
推荐答案
1416594600000对应于2014-11-21T18:30:00Z。换句话说,是2014年11月21日下午6点30分(UTC)。 Epoch Converter 是检查此类问题的好资源。
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.
现在,一个 Date
对象本身没有任何时区信息。它只是代表一个时间点。听起来您的 2014年11月22日值可能是在 local 时区(印度?)的午夜。如果您要从许多不同的时区中生成值,而又不存储哪个时区与哪个值对应,那么您在这里实际上就失去了一些信息。
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.
如果您正在尝试仅表示日期(而不是时间点),但是由于unix-epoch值必须将其存储为毫秒,所以存储午夜可能有意义日期(以UTC时间为准),尽管您也应该清楚地知道那是您在做什么。如果可以的话,您应该以某种方式存储该值,使其更明显地是一个日期,例如在数据库中使用 DATE
字段。日期和时间的工作实际上并不像我们担心的那样困难,因为如果您确切地知道要建模的数据,并在代码中的每个地方都非常清楚,就可以做到。
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.
一种使事情更清晰的方法是使用良好的日期/时间API,与 java.util.Date $ c $相比,它可以表示更多类型的数据。 c>和
java.util.Calendar
做。 Joda Time 对此非常有用,Java 8具有新的 java.time。*
API。我强烈建议您尽快移至其中之一。
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.
这篇关于在Java中将日期转换为毫秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!