LocalDateTime解析为纪元秒

时间:2019-03-02 20:52:36

标签: java java-8 localdate

我正在尝试将以下格式的字符串2010-10-12-18-43-55解析为自当前时区的纪元以来的秒数。这是我尝试过的

DateTimeFormatter dateTimeFormatter = 
          DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss");

我。

String datatetime = "2010-10-12-18-43-55";
Instant.parse(datetime).toEpochMilli; 
//Throws 
//java.time.format.DateTimeParseException: 
//Text '2010-10-12-18-43-55' could not be parsed at index 10

II。

String datatetime = "2010-10-12-18-43-55";
Instant.from(LocalDateTime.parse(datetime, dateTimeFormatter)).toEpochMilli
//Throws 
//java.time.DateTimeException: Unable to obtain Instant from 
//TemporalAccessor: 2010-10-12T18:43:55 of type 
//java.time.LocalDateTime type java.time.LocalDateTime

III。

String datatetime = "2010-10-12-18-43-55";
Instant.from(dateTimeFormatter.parse(datetime, new ParsePosition(0))).toEpochMilli
//Throws 
//java.time.DateTimeException: Unable to obtain Instant from 
//TemporalAccessor: {},ISO resolved to 2010-10-12T18:43:55 
//of type java.time.format.Parsed

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

  1. Instant javadocs中,String的格式必须为2007-12-03T10:15:30.00Z
  2. 由于缺少时区,因此无法将String解析为Instant。尝试这个: ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, ZoneId.systemDefault());
  3. 我不确定您要做什么。