2016-07-23 161 views
0

我有一個奇怪的問題,解析字符串到localdatetime解析字符串localdatetime

import java.time.LocalDateTime; 
import java.time.format.DateTimeFormatter; 

public class Main { 

    public static void main(String args[]) 
    { 
     DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_TIME; 
     LocalDateTime.parse("00:00",formatter); 
    } 

} 

時給我:

Exception in thread "main" java.time.format.DateTimeParseException: Text '00:00' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 00:00 of type java.time.format.Parsed 
    at java.time.format.DateTimeFormatter.createError(Unknown Source) 
    at java.time.format.DateTimeFormatter.parse(Unknown Source) 
    at java.time.LocalDateTime.parse(Unknown Source) 
    at Main.main(Main.java:9) 
Caused by: java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 00:00 of type java.time.format.Parsed 
    at java.time.LocalDateTime.from(Unknown Source) 
    at java.time.format.Parsed.query(Unknown Source) 
    ... 3 more 
Caused by: java.time.DateTimeException: Unable to obtain LocalDate from TemporalAccessor: {},ISO resolved to 00:00 of type java.time.format.Parsed 
    at java.time.LocalDate.from(Unknown Source) 
    ... 5 more 

我想與格式解析字符串「時:分」到一個localdatetime(24H格式)。我不在乎每月/每年/每天是什麼樣的,我只想要時間。

+0

似乎您的數據「00:00」與ISO_LOCAL_TIME強加的格式不兼容。 – user1929959

回答

5

我不在乎月/年/日是什麼樣的,我只想要時間。

表明您應該來解析它作爲一個LocalTime,因爲這就是字符串實際上代表。然後,您可以添加任何LocalDate把它拿到LocalDateTime,如果你真的假裝你有更多的信息,那麼你必須:

import java.time.*; 
import java.time.format.*; 

public class Test {  
    public static void main(String args[]) { 
     DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_TIME; 
     LocalTime time = LocalTime.parse("00:00",formatter); 
     LocalDate date = LocalDate.of(2000, 1, 1); 
     LocalDateTime dateTime = date.atTime(time); 
     System.out.println(dateTime); // 2000-01-01T00:00 
    } 
} 

如果你能避免創建LocalDateTime可言,只是工作與LocalTime,那會更好。

+0

哦,我不知道LocalTime類。 – amchacon