我有两个日期,在下面的格式中,月份是3个字母字符串。
1988年7月21日 2016年-12月18日
如何以上述格式计算日期之间的年数?
我能够用Joda时间计算月份为整数的年份之间的差异,如下所示
val y = Years.yearsBetween(new LocalDate("1988-12-21"), new LocalDate("2016-1-18"))
println( y.getYears)
Output: 27发布于 2016-05-13 15:14:30
使用DateTimeFormat调用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")))发布于 2016-05-13 15:16:04
下面是如何使用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发布于 2016-05-13 15:02:09
您可以使用的蛮力方法只是将字母字符串转换为正确的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;
}}
https://stackoverflow.com/questions/37213299
复制相似问题