public static void main(String[] args) throws ParseException {
//格式化日期的对象(转化成习惯的时间格式)
SimpleDateFormat sdFormat=new SimpleDateFormat("yyyy-MM-dd");
//静态方法getInstance()使用默认时区和语言环境获得一个日历。
Calendar calendar=Calendar.getInstance();
//输出当前系统时间;
System.out.println("当前系统时间: "+sdFormat.format(calendar.getTime()));
//add()增加日期,以天为单位(Calendar封装了很多静态的操作时间的单位)
//增加10天,负数则为减少天数
calendar.add(Calendar.DATE,15);
//输出增加10天后的时间;
System.out.println("增加15天后的时间: "+sdFormat.format(calendar.getTime()));
//输出3个月前的时间;
calendar.add(Calendar.MONTH, 16);
System.out.println("16个月前的时间: "+sdFormat.format(calendar.getTime()));
//输出时间为2020年的第100天
Date date=sdFormat.parse("2020-01-01");
calendar.setTime(date);
calendar.add(Calendar.DATE, 99);
System.out.println("2020年的第100天: "+sdFormat.format(calendar.getTime()));
}
比较大小
public boolean compare(String time1,String time2) throws ParseException
{
//如果想精确比较日期则写成"yyyy-MM-dd hh:mm:ss"就可以了
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd ");
//将字符串形式的时间转化为Date类型的时间
Date a=sdf.parse(time1);
Date b=sdf.parse(time2);
//Date类的一个方法,如果a早于b返回true,否则返回false
if(a.before(b))
return true;
else
return false;
/*
* 也可以根据将Date转换成毫秒进行比较
if(a.getTime()-b.getTime()<0)
return true;
else
return false;
*/
}