将日期转换为时间戳会返回错误的日期

时间:2019-12-28 16:35:09

标签: java android date

我有以下应返回时间戳的函数。当使用如下斜杠以字符串格式输入日期时,此代码有效:但在使用new Date(year, month, day).

时,此代码无法正常工作
import java.util.Date;

public static Long dateToTimestamp(Date date) {
        return date == null ? null : date.getTime();
}
dateToTimestamp(new Date(2019, 3, 4) ---> 61512498000000 or, when converted, Friday, April 4, 3919 5:00:00 AM

这是怎么回事?

3 个答案:

答案 0 :(得分:1)

调用Date(int year, int month, int date)时,参数应如下所示:

@param   year    the year minus 1900.
@param   month   the month between 0-11.
@param   date    the day of the month between 1-31.

Date(int year, int month, int date)起已弃用,您可以像下面那样使用Calendarset来获得所需的date

Calendar calendar = Calendar.getInstance()
calendar.set(2019, Calendar.MARCH, 4)
Long timeInMillis = calendar.timeInMillis

// timeInMillis should be 1551718624170 equivalent to Mon Mar 04 2019

答案 1 :(得分:1)

tl; dr

如果您要获取该日期当天的第一点(以UTC表示),请转换为自1970-01-01T00:00Z以来的毫秒数:

LocalDate             // Represent a date, without time-of-day and without time zone.  
.of( 2019 , 3 , 4 )   // Determine a date. Uses sane numbering, 1-12 for January-December.
.atStartOfDay(        // Determine first moment of the day.
    ZoneOffset.UTC    // Get the first moment as seen at UTC (an offset of zero hours-minutes-days.
)                     // Returns a `ZonedDateTime` object.
.toInstant()          // Convert from a `ZonedDateTime` to a simple `Instant` object, which is always in UTC, and has methods to get count-from-epoch.
.toEpochMilli()       // Get a count of milliseconds since the epoch reference of first moment of 1970 to UTC.

java.time

您使用的是可怕的日期时间类,而这些类在几年前已被JSR 310中定义的现代 java.time 类取代。

要获取自1970年1月UTC 1970-01-01T00:00Z的1970年第一时刻的纪元参考以来的毫秒数或整秒数,请使用Instant

long millis = Instant.now().toEpochMilli() ;

或者:

long seconds = Instant.now().getEpochSecond() ;

对于日期,您必须确定该日期的第一天。时间并非总是00:00,因此让 java.time 确定该时刻。这样做需要一个时区。每天从东部开始的时间要比从西部开始的时间早,在全球各地时区不同。

LocalDate ld = LocalDate.of( 2019 , 3 , 4 ) ;
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ld.atStartOfDay( z ) ;
Instant instant = zdt.toInstant() ;
long millis = Instant.now().toEpochMilli() ;

关于 java.time

java.time框架已内置在Java 8及更高版本中。这些类取代了麻烦的旧legacy日期时间类,例如java.util.DateCalendarSimpleDateFormat

要了解更多信息,请参见Oracle Tutorial。并在Stack Overflow中搜索许多示例和说明。规格为JSR 310

目前位于Joda-Timemaintenance mode项目建议迁移到java.time类。

您可以直接与数据库交换 java.time 对象。使用符合JDBC driver或更高版本的JDBC 4.2。不需要字符串,不需要java.sql.*类。

在哪里获取java.time类?

Table of which java.time library to use with which version of Java or Android

答案 2 :(得分:0)

遵循Date方法的JavaDoc。它指出,第一个参数年的值应为

  

the year minus 1900.

因此,调用 dateToTimestamp 方法的正确版本为

dateToTimestamp(new Date(119, 3, 4)

这将给您1554316200000。转换后的日期为2019年4月4日。

请注意,该月份的值从1月的0开始,2月的1开始,依此类推。