java日期处理小例子

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DaysPeriod {
	public static void main(String[] args) {
		
		Date now = new Date();
		Long fiveDaysAgo = now.getTime() - 1000 * 60 * 60 * 24 * 5;//5天前
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(fiveDaysAgo);
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.getTime();//5天前的 00:00:00
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-ddHH:mm:ss");

         //看一下效果
		System.out.println(sdf.format(calendar.getTime()));//2011-07-17 00:00:00
		
		//days==0,表示得到的是今天==1,昨天...
		int days=(int((now.getTime()-calendar.getTimeInMillis())/(1000*60*60*24));
		
		System.out.println(days);//这里肯定等于5
		
		
	}
}

你可能感兴趣的:(java)