java中对日期进行加减操作
程序员文章站
2022-06-24 21:56:09
...
package cn.cfm.demo.Test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* @Description: 对日期进行加减操作
* @Author:
* @Date: 2021/2/20
*/
public class DataShield {
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//获取系统日期
Calendar rightNow = Calendar.getInstance();
//指定某一天,比如2021-02-16
Date shouldDate = sdf.parse("2021-02-16");
//系统日期减少或者增加几天
rightNow.add(Calendar.DATE, -9);
System.out.println(sdf.format(rightNow.getTime()));
Calendar rightNow2 = Calendar.getInstance();
rightNow2.add(Calendar.DATE, -4);
System.out.println(sdf.format(rightNow2.getTime()));
System.out.println("=========================");
System.out.println(sdf.parse(sdf.format(rightNow.getTime())).getTime());
System.out.println(shouldDate.getTime());
System.out.println(rightNow2.getTime().getTime());
//sdf.parse(sdf.format(rightNow.getTime())).getTime()指以系统日期减少几天后,获取它的日期的getTime()而不是当前时间的getTime()
if(sdf.parse(sdf.format(rightNow.getTime())).getTime() <= shouldDate.getTime()
&& shouldDate.getTime() <= rightNow2.getTime().getTime()) {
System.out.println("成功");
}else{
System.out.println("失败");
}
}
}
输出结果
注意红框中的值,这样得到的是获取它的日期的getTime()而不是当前时间的getTime()
上一篇: awk入门指南