package com.xcfh.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
*
* @ClassName: BeforeOrAfterDate
*
* @Description: 得到當前輸入日期前(後)x天的日期
* @author PineTree
* @date 2014年12月29日 下午3:52:46
* @version
*/
public class BeforeOrAfterDate {
/**
*
* 查詢當前日期前(後)x天的日期
*
* @param date 當前日期
* @param day 天數(若是day數爲負數,說明是此日期前的天數)
* @return yyyy-MM-dd
*/
public String beforNumDay(Date date, int day) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.DAY_OF_YEAR, day);
return new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
}
/**
*
* 查詢當前日期前(後)x天的日期
*
* @param date 當前日期
* @param day 天數(若是day數爲負數,說明是此日期前的天數)
* @return yyyyMMdd
*/
public String beforNumberDay(Date date, int day) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.DAY_OF_YEAR, day);
return new SimpleDateFormat("yyyyMMdd").format(c.getTime());
}
/**
* 查詢當前日期前(後)x天的日期
*
* @param millis 當前日期毫秒數
* @param day 天數(若是day數爲負數,說明是此日期前的天數)
* @return long 毫秒數只顯示到天,時間全爲0
* @throws ParseException
*/
public long beforDateNum(long millis, int day) throws ParseException {
Calendar c = Calendar.getInstance();
c.setTimeInMillis(millis);
c.add(Calendar.DAY_OF_YEAR, day);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date(c.getTimeInMillis());
Date newDate = sdf.parse(sdf.format(date));
return newDate.getTime();
}
/**
* 查詢當前日期前(後)x天的日期
*
* @param millis 當前日期毫秒數
* @param day 天數(若是day數爲負數,說明是此日期前的天數)
* @return yyyy-MM-dd
*/
public String beforLongDate(long millis, int day) {
Calendar c = Calendar.getInstance();
c.setTimeInMillis(millis);
c.add(Calendar.DAY_OF_YEAR, day);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date(c.getTimeInMillis());
return sdf.format(date);
}
public static void main(String[] args) {
try{
BeforeOrAfterDate bd = new BeforeOrAfterDate();
long nowDate = System.currentTimeMillis();
System.out.println("nowDate = " + nowDate);
long beforDate = bd.beforDateNum(nowDate, 3);
System.out.println("beforDate = " + beforDate);
Date date = new Date(beforDate);
System.out.println("毫秒值結果日期 = " + date.toLocaleString());
System.out.println("yyyyMMdd結果日期 = " + bd.beforNumberDay(new Date(nowDate), 3));
System.out.println("yyyy-MM-dd結果日期 = " + bd.beforNumDay(new Date(nowDate), 3));
System.out.println("毫秒值獲取日期結果 = " + bd.beforLongDate(nowDate, 3));
}catch(Exception e) {
e.printStackTrace();
}
}
}
java