【问题标题】:Get number of years with a date in ISO8601 [duplicate]获取ISO8601中日期的年数[重复]
【发布时间】:2020-06-21 16:39:02
【问题描述】:

我正在尝试获取自提供“2013-12-06”格式的字符串的日期以来的年数。我想将它与今天(2020-21-06)进行比较,并有我可以放入 int 的年数。

例如,我收到

字符串 d = "2013-12-06"

今天的日期是 2020/21/06。

如何获得两者之间的年差?

在本例中为 6 年。

非常感谢!

【问题讨论】:

  • 显示您尝试过的内容以及遇到的问题
  • Rebi Khalifa - 这将是 7 年,而不是 6 年。

标签: java date iso8601


【解决方案1】:

java.time.Year

import java.time.Year;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

public class Main {
    public static void main(String[] args) {
        Year year = Year.parse("2013-12-06", DateTimeFormatter.ISO_DATE);
        long years = year.until(Year.now(), ChronoUnit.YEARS);

        System.out.println(years);
    }
}

输出:

7

【讨论】:

    【解决方案2】:
    import java.time.LocalDate;
    import java.lang.Math;
    import java.lang.Integer;
    
    public class Main {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            LocalDate now = LocalDate.now();
            String nowTime = now.toString();
            String d = "2013-12-06";
            String year = d.substring(0, 4);
            String NowYear = nowTime.substring(0, 4);
            int yearInt = Integer.parseInt(year);
            int NowYearInt = Integer.parseInt(NowYear);
            
            int diff = NowYearInt - yearInt;
            System.out.println(diff);
        }
    
    }
    

    老式的方式。打印7。如果年份是从 1000 到 2020,则有效。

    【讨论】:

      猜你喜欢
      • 2012-04-17
      • 2017-09-29
      • 2012-01-30
      • 2010-12-31
      • 2019-06-30
      • 1970-01-01
      • 1970-01-01
      • 2015-09-12
      • 2021-05-04
      相关资源
      最近更新 更多