1. 程式人生 > >日期時間處理

日期時間處理

目錄

1.日期加加減

2.遍歷最近15天

3.遍歷兩個日期


1.日期加加減

   //獲取時間加一年或加一月或加一天
    Date date = new Date();
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);//設定起時間
    //System.out.println("111111111::::"+cal.getTime());
    cal.add(Calendar.YEAR, 1);//增加一年
    cd.add(Calendar.DATE, n);//增加一天  
    cd.add(Calendar.DATE, -10);//減10天  
    cd.add(Calendar.MONTH, n);//增加一個月   
    System.out.println("輸出::"+cal.getTime());

2.遍歷最近15天

Calendar calendar = Calendar.getInstance();
calendar.setTime(HikDateUtils.getTimesmorning());

for (int i = 0; i < 15; i++) {
    calendar.add(Calendar.DATE, -1);
    dateList.add(HikDateUtils.getDateString(calendar.getTime(), "yyyy-MM-dd"));
}

3.遍歷兩個日期

public static void main(String[] args) {

    Calendar start = Calendar.getInstance();
    start.set(2016, 3, 10);
    Long startTIme = start.getTimeInMillis();

    Calendar end = Calendar.getInstance();
    end.set(2016, 4, 10);
    Long endTime = end.getTimeInMillis();

    Long oneDay = 1000 * 60 * 60 * 24l;

    Long time = startTIme;
    while (time <= endTime) {
        Date d = new Date(time);
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println(df.format(d));
        time += oneDay;
    }
}