53

如何指定格式字符串以单独从字符串转换日期。就我而言,只有日期部分是相关的

将其构造为DateTime失败:

String dateString = "2009-04-17";
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");
DateTime dateTime = formatter.parseDateTime(dateString);

有错误java.lang.IllegalArgumentException: Invalid format: "2011-04-17" is too short

可能是因为我应该LocalDate改用。但是,我没有看到任何LocalDate. String dateString = "2009-04-17";转换成的最佳方式是什么LocalDate(如果不是正确的表示形式,则为其他方式)

谢谢...

4

6 回答 6

59

您可能正在寻找LocalDate(Object). 这有点令人困惑,因为它需要一个 generic Object,但文档表明如果你将 a 传递给构造函数,它将使用ConverterManager知道如何处理 a 的a ,例如StringString

LocalDate myDate = new LocalDate("2010-04-28");
于 2010-04-27T13:58:57.620 回答
20

使用parse(String)方法。

LocalDate date = LocalDate.parse("2009-04-17");
于 2013-08-22T11:05:05.787 回答
10

LocalDate.parse()使用or有一个微妙的错误问题new LocalDate()。一个代码片段值一千字。在 scala repl 的以下示例中,我想以字符串格式 yyyyMMdd 获取本地日期。LocalDate.parse()很高兴给我一个 LocalDate 的实例,但它不是正确的(new LocalDate()具有相同的行为):

scala> org.joda.time.LocalDate.parse("20120202")
res3: org.joda.time.LocalDate = 20120202-01-01

我给它 2016 年 2 月 2 日,格式为 yyyyMMdd,我得到的日期是 20120202 年 1 月 1 日。我在这里很危险:我认为这不是它应该做的。Joda 使用 'yyyy-MM-dd' 作为默认值,但会隐含地接受没有 '-' 字符的字符串,认为你想要那年的 1 月 1 日?对我来说,这似乎不是一个合理的默认行为。

鉴于此,在我看来,使用不容易被愚弄的 joda 日期格式化程序是解析字符串的更好解决方案。此外,LocalDate.parse()如果日期格式不是“yyyy-MM-dd”,则可能会引发异常:

scala> val format = org.joda.time.format.DateTimeFormat.forPattern("yyyyMMdd")
format: org.joda.time.format.DateTimeFormatter = org.joda.time.format.DateTimeFormatter@56826a75

scala> org.joda.time.LocalDate.parse("20120202", format)
res4: org.joda.time.LocalDate = 2012-02-02

这将导致其他格式失败,因此您不会遇到这种奇怪的错误行为:

scala> val format = org.joda.time.format.DateTimeFormat.forPattern("yyyy-MM-dd")
format: org.joda.time.format.DateTimeFormatter = org.joda.time.format.DateTimeFormatter@781aff8b

scala> org.joda.time.LocalDate.parse("20120202", format)
java.lang.IllegalArgumentException: Invalid format: "20120202" is too short
  at org.joda.time.format.DateTimeFormatter.parseLocalDateTime(DateTimeFormatter.java:900)
  at org.joda.time.format.DateTimeFormatter.parseLocalDate(DateTimeFormatter.java:844)
  at org.joda.time.LocalDate.parse(LocalDate.java:179)
  ... 65 elided

这比返回 20120202 年的日期要理智得多。

于 2016-02-12T00:41:13.537 回答
5

就我而言,传入的字符串可能是两种格式之一。所以我首先尝试用更具体的格式解析字符串:

String s = "2016-02-12";
LocalDateTime ldt;
try {
    ldt = LocalDateTime.parse(s, DateTimeFormat.forPattern("YYYY-MM-dd HH:mm"));
}
catch (IllegalArgumentException e) {
    ldt = LocalDateTime.parse(s, DateTimeFormat.forPattern("YYYY-MM-dd"));
}
于 2016-02-12T06:58:56.857 回答
1

您可以使用LocalDate.of作为单独参数传递的年、月和日:

LocalDate date1 = LocalDate.of(2009, 4, 17);
LocalDate date2 = LocalDate.of(2009, Month.APRIL, 17);
于 2015-12-07T12:19:13.107 回答
0

这对我有用:

LocalDate d1 = LocalDate.parse("2014-07-19");
LocalDate dNow = LocalDate.now();  // Current date
于 2014-07-13T18:57:20.343 回答