Java 日期的差以及加减

版权声明:最终解释权归属Hern所有,恒! https://blog.csdn.net/qq_36761831/article/details/82750618

两个日期之间的差

使用静态方法 Period.between(start, end)  来求两个LocalDate型日期之间的差。

package com.Hern;
import java.util.*;
import java.time.*;
import java.time.format.DateTimeFormatter;

public class Test {
    
    public static void main(String[] args) {
    	LocalDate late = LocalDate.of(1997, 10, 04);//定义一个起始日期
    	LocalDate now = LocalDate.now();//定义一个结束日期
    	Period per = Period.between(late, now);//两者之间的差
    	System.out.println(per);//输出:P20Y11M13D
    	System.out.println(per.getYears()+"年"+per.getMonths()+"月"+per.getDays()+"日");//输出:20年11月13日
    }
    
}  

日期或日历的加减

使用LocalDate.plus(Period.ofDays(N)) 或 LocalDate.minus(Period.ofDays(N)) 实现日期的修改,从而创建一个过去或未来的时间。

plus()方法用于加

minus()方法用于减

package com.Hern;
import java.util.*;

import javax.swing.plaf.synth.SynthScrollBarUI;

import java.time.*;
import java.time.format.DateTimeFormatter;

public class Test {
    
    public static void main(String[] args) {
    	LocalDate date = LocalDate.now();//获取现在的日期
    	LocalDate then = date.plus(Period.ofDays(365));//计算现在的日期加上365天
    	System.out.println(then);//输出:2019-09-17
    	
    	LocalDate before = date.minus(Period.ofYears(2));//计算现在的日期减去2年
    	System.out.println(before);//输出:2016-09-17
    }
    
}  

猜你喜欢

转载自blog.csdn.net/qq_36761831/article/details/82750618