【问题标题】:Get the number of months beetween a date and today in JAVA [duplicate]在JAVA中获取日期和今天之间的月数[重复]
【发布时间】:2020-07-14 02:16:56
【问题描述】:

我正在尝试获取作为参数发送的字符串格式(“2019-05-31”)的给定日期与今天:2020-07-13 之间的月数。在本例中为 13 个月。

我想把答案放在一个 int 变量中。

有什么简单的方法吗?

非常感谢!

【问题讨论】:

  • @Niroshan 可怕的 Date 类都在几年前被现代的 java.time 类所取代,几年前采用了 JSR 310。建议在 2020 年使用它们是糟糕的建议。
  • 这个好像没研究好?有一些类似的问题,例如Java Date month differenceThis answer by Kuchi wold 可能会有所帮助。

标签: java date date-formatting monthcalendar


【解决方案1】:

从 Java 1.8 开始:

LocalDate today = LocalDate.now();
LocalDate myDate = LocalDate.parse("2019-05-31");
int months = (int) Period.between(myDate,today).toTotalMonths();
System.out.println(months); // output: 13

【讨论】:

【解决方案2】:

java.time

使用 java.time 类。

Period::toTotalMonths 方法返回一个 long,表示整个时间跨度内经过的月数。

您要求的是int,而不是long。与其将long 转换为您想要的int,不如调用Math.toIntExact。如果转换产生的缩小溢出,此方法将引发异常。

int months =
    Math.toIntExact(
        Period.between
        (
            LocalDate.parse( "2019-05-31" ) ,
            LocalDate.now( ZoneId.of( "Africa/Tunis" ) )
        )
        .toTotalMonths()
    )
;

【讨论】:

    【解决方案3】:

    您可以使用以下方法

    import java.time.LocalDate;
    import java.time.format.DateTimeFormatter;
    import java.time.temporal.ChronoUnit;
    
    public class DateUtil{
    
        public static void main(String[] args) {
    
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String date = "2019-05-31";
            LocalDate localDate = LocalDate.parse(date, formatter);
            LocalDate now = LocalDate.now();
    
            long diff = ChronoUnit.MONTHS.between(localDate, now);
    
            System.out.println(diff);
    
        }
    }
    
    

    【讨论】:

    • 无需为标准 ISO 8601 格式定义自定义格式模式。内置。
    猜你喜欢
    • 1970-01-01
    • 2017-09-11
    • 2023-01-31
    • 2018-04-14
    • 2019-11-07
    • 2013-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多