如果月份是 3 个字母的字符串,如何计算 2 个日期之间的年数
How to calculate the number of years between 2 dates if the month is a 3 letter string
我有 2 个日期,格式如下,其中月份是 3 个字母的字符串
1988-Jul-21
2016-Dec-18
如何计算上述格式中日期之间的年数?
当月份是整数时,我能够使用如下所示的 Joda 时间计算年份中日期之间的差异
val y = Years.yearsBetween(new LocalDate("1988-12-21"), new LocalDate("2016-1-18"))
println( y.getYears)
Output: 27
您可以使用的一种强力方法是将字母字符串简单地转换为正确的 int 值。您可以像这样使用数组。
String[11] months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
然后您可以循环查找当前月份何时与其中一个月份匹配,然后取 i val + 1(因为它基于零)。
在我看来,这比必须写出 12 个 if 语句要好。
for (int i = 0; i < months.length; i++) {
//where monthStr is a String that is the 3 letter month representaton
if (monthStr = months[i]) {
int monthInt = i + 1;
}
}
您使用了DateTimeFormat
to invoke the LocalDate.parse(String, DateTimeFormatter)
方法。像,
val y = Years.yearsBetween(
LocalDate.parse("1988-Jul-21", DateTimeFormat.forPattern("yyyy-MMM-dd")),
LocalDate.parse("2016-Dec-18", DateTimeFormat.forPattern("yyyy-MMM-dd")))
以下是如何使用 DateTimeFormatter 解析日期来处理纯 Java 8:
// The formatter to use when parsing the dates with a locale
// defined to prevent failures on non english environment
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MMM-dd", Locale.US);
System.out.println(
ChronoUnit.YEARS.between(
LocalDate.parse("1988-Jul-21", formatter),
LocalDate.parse("2016-Dec-18", formatter)
)
);
输出:
28
我有 2 个日期,格式如下,其中月份是 3 个字母的字符串
1988-Jul-21
2016-Dec-18
如何计算上述格式中日期之间的年数?
当月份是整数时,我能够使用如下所示的 Joda 时间计算年份中日期之间的差异
val y = Years.yearsBetween(new LocalDate("1988-12-21"), new LocalDate("2016-1-18"))
println( y.getYears)
Output: 27
您可以使用的一种强力方法是将字母字符串简单地转换为正确的 int 值。您可以像这样使用数组。
String[11] months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
然后您可以循环查找当前月份何时与其中一个月份匹配,然后取 i val + 1(因为它基于零)。
在我看来,这比必须写出 12 个 if 语句要好。
for (int i = 0; i < months.length; i++) {
//where monthStr is a String that is the 3 letter month representaton
if (monthStr = months[i]) {
int monthInt = i + 1;
}
}
您使用了DateTimeFormat
to invoke the LocalDate.parse(String, DateTimeFormatter)
方法。像,
val y = Years.yearsBetween(
LocalDate.parse("1988-Jul-21", DateTimeFormat.forPattern("yyyy-MMM-dd")),
LocalDate.parse("2016-Dec-18", DateTimeFormat.forPattern("yyyy-MMM-dd")))
以下是如何使用 DateTimeFormatter 解析日期来处理纯 Java 8:
// The formatter to use when parsing the dates with a locale
// defined to prevent failures on non english environment
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MMM-dd", Locale.US);
System.out.println(
ChronoUnit.YEARS.between(
LocalDate.parse("1988-Jul-21", formatter),
LocalDate.parse("2016-Dec-18", formatter)
)
);
输出:
28