package test;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateCal {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
/**
* 当前日期
*/
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE,-3);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String now = sdf.format(cal.getTime());
System.out.println("当前时间:"+now);
/**
* 日期相减
*/
cal.set(2008, 01, 01);
Date d1 = cal.getTime();
cal.set(2008, 03, 01);
Date d2 = cal.getTime();
long daterange = d2.getTime() - d1.getTime();
long time = 1000*3600*24; //A day in milliseconds
System.out.println("相差"+daterange/time+"天");
System.out.println("相差"+daterange/time/30+"个月");
/**
* 日期相加
*/
sdf = new SimpleDateFormat("yyyy-MM-dd");
cal.setTime(sdf.parse("2008-01-01"));
cal.add(Calendar.DAY_OF_MONTH, +5);
String result = sdf.format(cal.getTime());
System.out.println("相加/减后的日期:"+result);
}
}
返回结果:
当前时间:2008-01-05 09:50:37
相差60天
相差2个月
相加/减后的日期:2008-01-06