java GMT 日期时间解析

我有一个像下面这样的字符串


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)


眼眸繁星
浏览 131回答 3
3回答

慕慕森

你的格式化程序的模式是错误的。缺少年份 ( "yyyy") 且时区不匹配。要匹配它,您需要同时使用两者z,并且Z还需要为 GMT 添加不匹配的文本,例如"'GMT'Z (z)".试试这个:"E MMM dd yyyy HH:mm:ss 'GMT'Z (z)"

手掌心

正如您在这里看到的,您可以使用以下模式: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

慕丝7291255

由于您只需要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)));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java