我试过这个:
DateFormat fmt = new SimpleDateFormat("MMMM dd, yyyy");
Date d = fmt.parse("June 27, 2007");
错误:
Exception in thread "main" java.text.ParseException: Unparseable date: "June 27, 2007"
java文档说我应该使用四个字符来匹配完整的表单。我只能成功地使用MMM,像"Jun“这样缩短的月份,但我需要匹配完整的形式。
文本:对于格式,如果图案字母的数目是4个或更多,则使用完整的表单;如果可用,则使用简短的表单。对于解析,两种表单都被接受,与模式字母的数量无关。
https://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
发布于 2021-02-13 01:20:22
LocalDate来自java.time
使用来自LocalDate
的java.time (现代java.time和time )作为日期
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MMMM d, u", Locale.ENGLISH);
LocalDate date = LocalDate.parse("June 27, 2007", dateFormatter);
System.out.println(date);
输出:
2007-06-27
正如其他人已经说过的,当您的字符串使用英语时,请记住指定一个讲英语的语言环境。LocalDate
是一天中没有时间的日期,因此比旧的Date
类更适合您的字符串中的日期。尽管名为Date
,但它并不代表一个日期,而是世界不同时区中至少有两个不同日期的时间点。
只有当您需要一个老式的Date
来进行API,而您现在无法负担升级到java.time时,才可以这样转换:
Instant startOfDay = date.atStartOfDay(ZoneId.systemDefault()).toInstant();
Date oldfashionedDate = Date.from(startOfDay);
System.out.println(oldfashionedDate);
在我的时区中输出:
2007年6月27日上午00:00:00
链接
Oracle教程:日期时间解释了如何使用java.time。
发布于 2010-02-07 17:43:26
您可能使用的是一个区域设置,其中月份名称不是“一月”、“二月”等,而是本地语言中的一些其他单词。
尝试指定您希望使用的区域设置,例如Locale.US
DateFormat fmt = new SimpleDateFormat("MMMM dd, yyyy", Locale.US);
Date d = fmt.parse("June 27, 2007");
此外,您在日期字符串中有一个额外的空间,但实际上这对结果没有任何影响。不管用哪种方式都行。
发布于 2015-03-12 05:41:26
仅仅是为了将其扩展到新的Java8API:
DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendPattern("MMMM dd, yyyy").toFormatter();
TemporalAccessor ta = formatter.parse("June 27, 2007");
Instant instant = LocalDate.from(ta).atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
Date d = Date.from(instant);
assertThat(d.getYear(), is(107));
assertThat(d.getMonth(), is(5));
更详细一些,但您也看到了所使用的日期方法被废弃了;-)继续前进的时间。
https://stackoverflow.com/questions/2219139
复制