簡體   English   中英

使用Java 8 DateTimeFormatter將字符串轉換為LocalDateTime

[英]Converting String into LocalDateTime using Java 8 DateTimeFormatter

我使用的是Java 8, .txt文件中有一個字符串,我想將其轉換為LocalDateTime對象。

String time1 = "2017-10-06T17:48:23.558";

DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("dd.MM.yyyy. HH:mm:ss");
LocalDateTime alarmTime = LocalDateTime.parse(time1, formatter1);

System.out.println(time1);

這給了我這個例外:

Exception in thread "main" java.time.format.DateTimeParseException: Text '2017-10-06T17:48:23.558' could not be parsed at index 2
at java.time.format.DateTimeFormatter.parseResolved0(Unknown Source)
at java.time.format.DateTimeFormatter.parse(Unknown Source)
at java.time.LocalDateTime.parse(Unknown Source)

有任何想法嗎?

PS注意:

DateTimeFormatter formatter = DateTimeFormat.forPattern("dd.MM.yyyy. HH:mm:ss");
DateTime dt = formatter.parseDateTime(string);

在Java 8中不起作用。

編輯:我沒有把問題弄清楚,我的壞:

我的.txt文件中有此字符串,我需要將其轉換為LocalDateTime對象以將其保存到類對象中,但是我需要以規定的格式將其打印在表中。 我不希望它以原始格式"2017-10-06T17:48:23.558"打印出來。 我希望它打印出類似以下內容: "10.06.2017. 17:48:23"

您想要輸出的格式( "dd.MM.yyyy. HH:mm:ss" )與輸入格式不同,因此無法使用它進行解析。

在這種情況下,輸入采用ISO8601格式 ,因此您可以直接對其進行解析。 然后,使用格式化程序將LocalDateTime對象格式化為所需的格式:

String time1 = "2017-10-06T17:48:23.558";
// convert String to LocalDateTime
LocalDateTime localDateTime = LocalDateTime.parse(time1);
// parse it to a specified format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy. HH:mm:ss");
System.out.println(localDateTime.format(formatter));

輸出為:

2017年6月10日。 17:48:23


PS:如果輸入的格式不同,則應使用一個格式化程序進行解析,而使用另一個格式化程序進行格式化。 檢查javadoc以查看所有可用格式。

使用LocalDateTime.parse而不使用任何其他格式將其解析為LocalDateTime

jshell> java.time.LocalDateTime ldt = java.time.LocalDateTime.parse("2017-10-06T17:48:23.558");
ldt ==> 2017-10-06T17:48:23.558

您的日期格式化程序模式錯誤。 您需要提供與傳遞的字符串相同的格式

例:

String date = "2016-08-16T10:15:30+08:00";

    ZonedDateTime result = ZonedDateTime.parse(date, DateTimeFormatter.ISO_DATE_TIME);

    System.out.println("ZonedDateTime : " + result);

    System.out.println("TimeZone : " + result.getZone());

    LocalDate localDate = result.toLocalDate();

    System.out.println("LocalDate : " + localDate);

您只是弄錯了模式。 如果您使用這樣的模式,它將起作用:

DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");

這些模式在Javadoc中有詳細記錄: https : //docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html

DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM