time function

1. SimpleDate function

parse parses the string into a Date type

format converts the Date type to a string

1) format function :

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Date now = new Date();
    String nowString = sdf.format(now);
    System.out.println("nowString: "+nowString);

output:

nowString: 2019-09-26

2) parse function :

 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
 Date startDate = sdf.parse("2018-05-10");

output:

date: Thu May 10 00:00:00 CST 2018

3) Calculate the difference in days between two time points :

    // 开始时间
    Date startDate = sdf.parse("2018-05-10");
    // 结束时间
    Date endDate = sdf.parse("2019-11-10");
    // 得到相差的天数 betweenDate
    long betweenDate = (endDate.getTime() - startDate.getTime()) / (60 * 60 * 24 * 1000);
    // 打印控制台相差的天数
    System.out.println("天数" + betweenDate);

2.LocalDate function :

// 开始时间
    Date startDate = sdf.parse("2018-05-10");
    // 结束时间
    Date endDate = sdf.parse("2019-11-10");
    // 得到相差的天数 betweenDate
    long betweenDate = (endDate.getTime() - startDate.getTime()) / (60 * 60 * 24 * 1000);
    // 打印控制台相差的天数
    System.out.println("天数" + betweenDate);

    LocalDate startLocalDate = startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    LocalDate endLocalDate = endDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    Period period = Period.between(startLocalDate,endLocalDate);
    //月份
    int monthBetween = period.getMonths();
    //年数
    int yearBetween = period.getYears();
    //相差天数
    double dayDiffer = period.getDays();
    //间隔的天数
    double dayInterval = endLocalDate.toEpochDay() - startLocalDate.toEpochDay();
    //间隔的月份
    int monthInterval = period.getMonths() + period.getYears() * 12;
    //年数,包含小数
    double yearBetweenDecimal = dayInterval/Double.valueOf(365);
    System.out.println("相差的月份:"+monthBetween);
    System.out.println("相差的年:"+yearBetween);
    System.out.println("相差的年份:"+dayDiffer);
    System.out.println("间隔的天数:"+dayInterval);
    System.out.println("间隔的月份:"+monthInterval);
    System.out.println("间隔的年:"+yearBetweenDecimal);

output:

天数549
相差的月份:6
相差的年:1
相差的年份:0.0
间隔的天数:549.0
间隔的月份:18
间隔的年:1.5041095890410958

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=324126779&siteId=291194637