使用SimpleDateFormat将没有时间的日期转换为毫秒时出现错误的小时数

时间:2019-05-10 07:37:05

标签: java date datetime

我正在尝试将Date转换为毫秒而没有时间戳。

   final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
   TimeZone timeZone = TimeZone.getTimeZone("Asia/Kolkata");
   sdf.setTimeZone(timeZone);
   Date dateObj = sdf.parse(date);
   System.out.println ("Milliseconds ="+ dateObj.getTime()) ;

输入: 2019-05-08

输出: Milliseconds = 1557253800000 // is 2019-05-08T12:00:00 not 2019-05-08T00:00:00

我想将"2019-05-08"转换为2019-05-08T00:00:00的毫秒数吗?任何解决方案。

1 个答案:

答案 0 :(得分:3)

1557253800000对应于2019-05-07T18:30:00Z。由于亚洲/加尔各答的时区比UTC早5:30小时,因此对应于2019-05-08T00:00:00+0530。那是您的代码按预期工作。

正如@Lino在Java 8注释中提​​到的那样,应使用新的java.time类而不是java.util.Date。这将是使用新的java.time API的相应代码:

String str = "2019-05-08";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate date = LocalDate.parse(str, formatter);

ZonedDateTime zonedDateTime = date.atStartOfDay(ZoneId.of("Asia/Kolkata"));
System.out.println(zonedDateTime.toInstant().toEpochMilli()); // will output 1557253800000

zonedDateTime = date.atStartOfDay(ZoneId.of("UTC"));
System.out.println(zonedDateTime.toInstant().toEpochMilli()); // will output 1557273600000