今天是2013年12月18日。通過添加減去毫秒數來獲取正確的日期
我正在測試這個程序,我想通過從System.currentMillis()
增加/減去數毫秒來得到另一個日期。當我在德布爾轉換日期時效果很好,但對於一些相似的值卻無法正確運行。例如下面的代碼給我2013 12 20
作爲結果!我想知道,不,我還在想如何可能!或者我犯了一個錯誤?
public class CreateDirFiles {
public static final String PLOG_DIR = "ProductLog";
private SimpleDateFormat dateFormatter = new SimpleDateFormat();
public CreateDirFiles() {
}
public void createDayDir(Date date){
dateFormatter.applyPattern("YYYY");
String year = dateFormatter.format(date);
dateFormatter.applyPattern("MM");
String month = dateFormatter.format(date);
dateFormatter.applyPattern("dd");
String day = dateFormatter.format(date);
System.out.printf("%s %s %s\n", year, month, day);
}
public static void main(String... args){
CreateDirFiles dfc = new CreateDirFiles();
dfc.createDayDir(new Date(System.currentTimeMillis() -
((long)(48 * 24 * 3600 * 1000))));
}
}
你正在重新發明車輪。使用'日曆'代替。 – m0skit0
無論如何,它應該很好地工作新的日期(毫秒)尚未棄用!使用日期或日曆不是主題。 – Johnny
不,它不適用於日期,因爲日期無法添加/減少時間。日曆確實。 – m0skit0