2017-02-10 11 views
2

で解析できませんでした私は、コードの一部を次のようしている。のJava 8日付/時間:瞬間、インデックス19

String dateInString = "2016-09-18T12:17:21:000Z"; 
Instant instant = Instant.parse(dateInString); 

ZonedDateTime zonedDateTime = instant.atZone(ZoneId.of("Europe/Kiev")); 
System.out.println(zonedDateTime); 

をそれは例外次のように私を与える:

スレッドの例外「メイン」をjava.utize.format.DateTimeParseException: テキスト '2016-09-18T12:17:21:000Z'をインデックス19で解析できませんでした。 でjava.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949) at java.time.format.DateTimeFormatter.parse(DateTimeForm atter.java:1851) core.domain.converters.TestDateTime.main(TestDateTime.java:10でjava.time.Instant.parse(Instant.java:395))で

私はその変化完全に停止への最後のコロン:

String dateInString = "2016-09-18T12:17:21.000Z"; 

...実行は罰金行く:

2016-09-18T15:17:21 + 03:00 [ヨーロッパ/キエフ]

ですから、質問はどのようにInstantDateTimeFormatterで日付を解析するのですか?

答えて

3

をチェックアウト「の問題は、」非標準(標準は小数点である)であるミリ秒前にコロン、です。カスタム形式のカスタムDateTimeFormatterを構築する必要があり

それを動作させるために、このコードの

String dateInString = "2016-09-18T12:17:21:000Z"; 
DateTimeFormatter formatter = new DateTimeFormatterBuilder() 
    .append(DateTimeFormatter.ISO_DATE_TIME) 
    .appendLiteral(':') 
    .appendFraction(ChronoField.MILLI_OF_SECOND, 3, 3, false) 
    .appendLiteral('Z') 
    .toFormatter(); 
LocalDateTime instant = LocalDateTime.parse(dateInString, formatter); 
ZonedDateTime zonedDateTime = instant.atZone(ZoneId.of("Europe/Kiev")); 
System.out.println(zonedDateTime); 

出力:

2016-09-18T12:17:21+03:00[Europe/Kiev] 

リテラルあなたの日時ではなく、ドットを持っていた場合最後のコロンのほうがはるかに単純になります。

+0

実際には、標準はCOMMA *または* FULL STOP(ピリオド)で、**カンマが優先されます**。 * ISO 8601:2004 *第3版2004-12-01のセクション「4.2.2.4小数部の表現」を参照してください。小数点以下の桁数は、整数部からISO 31-0で指定された小数点記号、コンマ[、]または完全停止[。]。これらのうち、コンマが優先記号です。ISOのためではなく、JDKでたぶん... –

+0

@basil、[小数点を使用する](http://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatterBuilder.html# appendFraction-java.time.temporal.TemporalField-INT-INT-boolean-) – Bohemian

1

使用SimpleDateFormat

String dateInString = "2016-09-18T12:17:21:000Z"; 
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss:SSS"); 
Instant instant = sdf.parse(dateInString).toInstant(); 
ZonedDateTime zonedDateTime = instant.atZone(ZoneId.of("Europe/Kiev")); 
System.out.println(zonedDateTime); 

2016-09-18T19:17:21 + 03:00 [ヨーロッパ/キエフ]

-1
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/MM/yyyy"); 

String date = "16/08/2016"; 

//convert String to LocalDate 
LocalDate localDate = LocalDate.parse(date, formatter); 

Stringが同様にフォーマットされている場合ISO_LOCAL_DATE、あなたは直接変換する必要はありません、文字列を解析することができます。

package com.mkyong.java8.date; 

import java.time.LocalDate; 

public class TestNewDate1 { 

    public static void main(String[] argv) { 

     String date = "2016-08-16"; 

     //default, ISO_LOCAL_DATE 
     LocalDate localDate = LocalDate.parse(date); 

     System.out.println(localDate); 

    } 

} 

このサイト Site here

+0

時間コンポーネントはどうですか? – Bohemian