Java:如何将带月份名称的字符串转换为DateTime?

时间:2013-09-30 01:03:25

标签: java parsing date datetime datetime-format

我看到答案可以让我转换格式就像

"14/02/1952 14:52:22"

使用DateTimeFormatter

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

如何将相同的想法应用于此格式的字符串:

"Sunday, September 29, 2013 7:59:58 AM PDT"

我正在尝试

DateTimeFormatter formatter = DateTimeFormat.forPattern"EEEE, MMMM dd, yyyy h:mm:ss a zzz";
DateTime dt = formatter.parseDateTime(string);

但它抱怨这个。

1 个答案:

答案 0 :(得分:6)

2018 / Java 10

String value = "Sunday, September 29, 2013 7:59:58 AM PDT";
String format = "EEEE, MMMM dd, yyyy h:mm:ss a zzz";

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
        .parseCaseInsensitive()
        .appendPattern(format)
        .toFormatter(Locale.US);
ZonedDateTime zdt = ZonedDateTime.parse(value, formatter);
System.out.println(zdt);
System.out.println(zdt.format(formatter));

打印

2013-09-29T07:59:58-07:00[America/Los_Angeles]
Sunday, September 29, 2013 7:59:58 AM PDT

原始答案

您需要更改预期格式以满足SimpleDateFormat

指定的要求
String value = "Sunday, September 29, 2013 7:59:58 AM PDT";
String format = "EEEE, MMMM dd, yyyy h:mm:ss a zzz";
SimpleDateFormat sdf = new SimpleDateFormat(format);
try {
    Date date = sdf.parse(value);
    System.out.println(date);
    System.out.println(sdf.format(date));
} catch (ParseException ex) {
    ex.printStackTrace();
}

哪些输出......

Mon Sep 30 00:59:58 EST 2013
Sunday, September 29, 2013 7:59:58 AM PDT