我使用 Java 8 解析日期,并找到两个日期之间的差异。
这是我的代码片段:
String date1 ="01-JAN-2017";
String date2 = "02-FEB-2017";
DateTimeFormatter df = DateTimeFormatter .ofPattern("DD-MMM-YYYY", en);
LocalDate d1 = LocalDate.parse(date1, df);
LocalDate d2 = LocalDate.parse(date2, df);
Long datediff = ChronoUnit.DAYS.between(d1,d2);
当我运行我得到的错误:
java.time.format.DateTimeParseException:无法在索引 3 处解析文本
首先,check the javadoc。大写的D
表示年中的天字段(不是您想要的月中的天),大写的Y
表示基于周的年字段(不是您想要的年)。
此外,您使用大写字母(JAN
和FEB
)的月份名称,因此您的格式化程序必须不区分大小写(默认行为是仅接受Jan
和Feb
)。这些月份名称是英语缩写,因此您还必须使用英语区域设置以确保正确使用。
所以,你的格式化程序应该是这样创建的:
DateTimeFormatter df = new DateTimeFormatterBuilder()
// case insensitive to parse JAN and FEB
.parseCaseInsensitive()
// add pattern
.appendPattern("dd-MMM-yyyy")
// create formatter (use English Locale to parse month names)
.toFormatter(Locale.ENGLISH);
这将使您的代码工作(和datediff
将32
)。
下面的代码工作。问题是你正在使用“JAN”而不是“Jan”DateTimeFormatter 不承认它似乎。并且还将模式更改为“d-MMM-yyyy”。
String date1 ="01-Jan-2017";
String date2 = "02-Feb-2017";
DateTimeFormatter df = DateTimeFormatter.ofPattern("d-MMM-yyyy");
LocalDate d1 = LocalDate.parse(date1, df);
LocalDate d2 = LocalDate.parse(date2, df);
Long datediff = ChronoUnit.DAYS.between(d1,d2);
Source:https://www.mkyong.com/java8/java-8-how-to-convert-string-to-localdate/

// DateTimeFormatterBuilder provides custom way to create a
// formatter
// It is Case Insensitive, Nov , nov and NOV will be treated same
DateTimeFormatter f = new DateTimeFormatterBuilder().parseCaseInsensitive()
.append(DateTimeFormatter.ofPattern("yyyy-MMM-dd")).toFormatter();
try {
LocalDate datetime = LocalDate.parse("2019-DeC-22", f);
System.out.println(datetime); // 2019-12-22
} catch (DateTimeParseException e) {
// Exception handling message/mechanism/logging as per company standard
}

也许有人正在寻找这将与日期格式,如3 / 24 / 2022或11 / 24 / 2022
DateTimeFormatter.ofPattern ("M / dd / yyyy")
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/dd/yyyy");
formatter = formatter.withLocale( Locale.US ); // Locale specifies human language for translating, and cultural norms for lowercase/uppercase and abbreviations and such. Example: Locale.US or Locale.CANADA_FRENCH
LocalDate date = LocalDate.parse("3/24/2022", formatter);
System.out.println(date);
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(27条)