Java GMT datetimeparse

时间:2019-06-06 12:09:01

标签: java zoneddatetime

我有一个类似以下的字符串

Fri May 31 2019 05:08:40 GMT-0700 (PDT)

我想将其转换为yyyy-MM-dd之类的东西。

我尝试过这个。

String date1 = "Fri May 31 2019 05:08:40 GMT-0700 (PDT)";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "E MMM dd HH:mm:ss z uuuu" ).withLocale( Locale.US );

ZonedDateTime zdt = ZonedDateTime.parse( date1 , f );
LocalDate ld = zdt.toLocalDate();
DateTimeFormatter fLocalDate = DateTimeFormatter.ofPattern( "yyyy-MM-dd" );
String output = ld.format( fLocalDate ) ;

我遇到了错误:

Exception in thread "main" java.time.format.DateTimeParseException: Text 
'Fri May 31 2019 05:08:40 GMT-0700 (PDT)' could not be parsed at index 13
at java.time.format.DateTimeFormatter.parseResolved0(Unknown Source)
at java.time.format.DateTimeFormatter.parse(Unknown Source)
at java.time.ZonedDateTime.parse(Unknown Source)

3 个答案:

答案 0 :(得分:1)

格式化程序的模式是错误的。年份缺少("yyyy")和时区不匹配。要匹配它,您需要同时使用zZ,还需要为GMT添加不匹配的文本,例如"'GMT'Z (z)"

尝试一下:

"E MMM dd yyyy HH:mm:ss 'GMT'Z (z)"

答案 1 :(得分:1)

您可以看到here,可以使用以下模式:

public static void main(String[] args) throws Exception {
    String date1 = "Fri May 31 2019 05:08:40 GMT-0700 (PDT)";
    DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM dd yyyy HH:mm:ss 'GMT'Z '('z')'" ).withLocale( Locale.US );

    ZonedDateTime zdt = ZonedDateTime.parse( date1 , f );
    LocalDate ld = zdt.toLocalDate();
    DateTimeFormatter fLocalDate = DateTimeFormatter.ofPattern( "yyyy-MM-dd" );
    String output = ld.format( fLocalDate ) ;
    System.out.println(output);
}

输出:

  

2019-05-31

答案 2 :(得分:-1)

由于您只需要 yyyy-MM-dd 格式的日期,请尝试以下代码:

   String date1 = "Fri May 31 2019 05:08:40 GMT-0700";

   //this format is good enough to read required data from your String
   DateFormat df1 = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss");

   //format you require as final output
   DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");

   //convert String to date ( with required attributes ) and then format to target
   System.out.println(df2.format(df1.parse(date1)));