简体   繁体   English

在Java中将日期转换为毫秒

[英]Convert Date to Milliseconds in Java

I need to convert a Date to its corresponding Milliseconds format.I am using getTime() method of Date class in Java for this. 我需要将Date转换为其相应的毫秒格式。为此,我在Java中使用Date类的getTime()方法。 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 . 我有22-Nov-2014 If I convert this date to milliseconds format then 1,416,594,600,000 is generated. 如果我将此日期转换为毫秒格式,则会生成1,416,594,600,000 Actually this value corresponds to 21-Nov-2014 . 实际上,此值对应于21-Nov-2014

Please help me to get an exact milliseconds value corresponds to a Date in java. 请帮助我获取与java中的Date相对应的确切毫秒值。

1416594600000 corresponds to 2014-11-21T18:30:00Z. 1416594600000对应于2014-11-21T18:30:00Z。 In other words, 6.30pm on November 21st 2014 in UTC . 换句话说,就是2014年11月21日下午6点30分(UTC) Epoch Converter is a great resource for checking things like that. Epoch Converter是检查此类问题的绝佳资源。

Now, a Date object doesn't have any time zone information itself. 现在, Date对象本身没有任何时区信息。 It just represents a point in time. 它只是代表一个时间点。 It sounds like your "22-Nov-2014" value was probably midnight in the local time zone (India?). 听起来您的“ 2014年11月22日”值可能是当地时区(印度?)的午夜。 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. 如果您只想表示一个日期(而不是时间点),但必须将其存储为毫秒数(因为unix-epoch以来的值),则可以将该日期的午夜存储在UTC中 ,尽管您也应该非常清楚地知道那就是您在做什么。 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字段。 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. 一种使事情更清楚的方法是使用一个良好的日期/时间API,该API允许您表示比java.util.Datejava.util.Calendar更多的数据。 Joda Time is good for this, and Java 8 has the new java.time.* API. Joda Time对此很有用,Java 8具有新的java.time.* API。 I'd strongly advise you to move to one of those as soon as possible. 我强烈建议您尽快移至其中之一。

tl;dr tl; dr

LocalDate.of( 2014 , Month.NOVEMBER , 22 )
         .atStartOfDay( ZoneId.of ( "Asia/Kolkata" ) )
         .toInstant()
         .toEpochMilli()

Details 细节

The Answer by Jon Skeet is correct and wise. 乔恩·斯基特答案是正确和明智的。

Here is some example code using java.time classes. 这是一些使用java.time类的示例代码。

LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone. LocalDate类表示没有日期和时区的仅日期值。

A time zone is crucial in determining a date. 时区对于确定日期至关重要。 For any given moment, the date varies around the globe by zone. 在任何给定时刻,日期都会在全球范围内变化。 For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec . 例如, 法国巴黎午夜过后几分钟是新的一天,而在魁北克蒙特利尔仍然是“昨天”。

ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );

You can specify a LocalDate . 您可以指定LocalDate

LocalDate ld = LocalDate.of( 2014 , Month.NOVEMBER , 22 );

ld.toString(): 2014-11-22 ld.toString():2014-11-22

ZonedDateTime

You desire a count-of-milliseconds-since-epoch. 您希望从纪元开始算起毫秒。 I do not recommend using a count-from-epoch for handling date-time. 建议使用从时代开始计数来处理日期时间。 But if you insist, here we go. 但是,如果您坚持要求,那么我们开始吧。

A count-from-epoch of milliseconds means we need a date and a time-of-day. 毫秒计数意味着我们需要一个日期一个时间。 We have a date. 我们有个约会。 I assume you want the first moment of the day as the time-of-day. 我假设您希望将当天的第一时间作为一天中的时间。 Do not assume this time is 00:00:00 . 不要以为这个时间是00:00:00 Anomalies such as Daylight Saving Time (DST) may mean the day starts at some other time such as 01:00:00 . 诸如夏令时(DST)之类的异常可能意味着这一天从其他时间开始,例如01:00:00 Let java.time determine that first moment by generating a ZonedDateTime object from a LocalDate . 让java.time通过从LocalDate生成ZonedDateTime对象来确定第一时刻。

LocalDate ld = LocalDate.of ( 2014 , Month.NOVEMBER , 22 );
ZoneId z = ZoneId.of ( "Asia/Kolkata" );
ZonedDateTime zdt = ld.atStartOfDay ( z );

zdt.toString(): 2014-11-22T00:00+05:30[Asia/Kolkata] zdt.toString():2014-11-22T00:00 + 05:30 [亚洲/加尔各答]

Instant

You can extract an Instant if desired. 如果需要,您可以提取一个Instant The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction). Instant类以UTC表示时间轴上的时刻,分辨率为纳秒 (最多十进制的九(9)位数字)。 A developer should think of UTC as the One True Time , and not think about their own parochial time zone while working. 开发人员应该将UTC视为“ 一个真实的时间” ,而不是在工作时考虑自己的狭区时区。

Instant instant = zdt.toInstant ();

instant.toString(): 2014-11-21T18:30:00Z Instant.toString():2014-11-21T18:30:00Z

From the instant we can ask for a count of milliseconds since epoch. 从那一刻起,我们就可以要求毫秒数。 Be aware this involves data-loss as any nanoseconds will be truncated to milliseconds. 请注意,这涉及数据丢失,因为任何纳秒都将被截断为毫秒。

long epochMillis = instant.toEpochMilli();

java.util.Date

I suggest avoiding the legacy date-time classes. 我建议避免使用旧的日期时间类。 But if you must , you can convert. 但是,如果必须 ,您可以进行转换。 Look to new methods added to the old classes like java.util.Date . 查看添加到旧类java.util.Date新方法,例如java.util.Date

java.util.Date utilDate = java.util.Date.from( instant );

About java.time 关于java.time

The java.time framework is built into Java 8 and later. java.time框架内置于Java 8及更高版本中。 These classes supplant the troublesome old legacy date-time classes such as java.util.Date , .Calendar , & java.text.SimpleDateFormat . 这些类取代了麻烦的旧式旧式日期时间类,例如java.util.Date.Calendarjava.text.SimpleDateFormat

The Joda-Time project, now in maintenance mode , advises migration to java.time. 现在处于维护模式Joda-Time项目建议迁移到java.time。

To learn more, see the Oracle Tutorial . 要了解更多信息,请参见Oracle教程 And search Stack Overflow for many examples and explanations. 并在Stack Overflow中搜索许多示例和说明。 Specification is JSR 310 . 规格为JSR 310

Where to obtain the java.time classes? 在哪里获取java.time类?

  • Java SE 8 and SE 9 and later Java SE 8SE 9及更高版本
    • Built-in. 内置的
    • Part of the standard Java API with a bundled implementation. 标准Java API的一部分,具有捆绑的实现。
    • Java 9 adds some minor features and fixes. Java 9添加了一些次要功能和修复。
  • Java SE 6 and SE 7 Java SE 6SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport . java.time的许多功能在ThreeTen- Backport中都被反向移植到Java 6和7。
  • Android 安卓系统

The ThreeTen-Extra project extends java.time with additional classes. ThreeTen-Extra项目使用其他类扩展了java.time。 This project is a proving ground for possible future additions to java.time. 该项目为将来可能在java.time中添加内容提供了一个试验场。 You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more . 您可以在这里找到一些有用的类,比如IntervalYearWeekYearQuarter ,和更多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM