Java: How to convert string with month name to DateTime?

点点圈 提交于 2019-12-31 03:47:11

问题


I've seen answers that let me convert when the format is like

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

by using DateTimeFormatter

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

How do I apply the same idea to strings of this format:

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

I am trying

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

but it's complaining about this.


回答1:


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));

Which prints

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

Original answer

You need to change the expected format to meet the requirements as specified by the 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();
}

Which outputs...

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


来源:https://stackoverflow.com/questions/19085073/java-how-to-convert-string-with-month-name-to-datetime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!