我實際上已經找到了最後三個日期,我想要做的是從每個日期減去5小時45分鐘。如何實現它?減去日期值的時間
到目前爲止,我已經做的代碼是:
public static List<Date> getPastThreeDays() {
List<Date> pDates = new ArrayList<Date>();
for (int i = 1; i <= 3; i++) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -i);
Date date = cal.getTime();
String pastDate = sdf.format(date);
Date pstThreesDates;
try {
pstThreesDates = sdf.parse(pastDate);
pDates.add(pstThreesDates);
} catch (ParseException e) {
e.printStackTrace();
}
}
return pDates;
}
public static void main(String[] args) throws ParseException {
// for getting past three dates
System.out.println("-----Formatted Past Three Days-----");
List<Date> pastThreeDatesList = getPastThreeDays();
for (Date date : pastThreeDatesList) {
System.out.println("Orignal:" + date);
}
提示:「Date」只是Unix時代以來的毫秒數。你可以通過調用getTime()來獲得該數字。然後可以在5小時45分鐘內減去毫秒數。然後你可以調用'setTime'或者創建一個新的'Date' ... –
你已經在使用'Calendar.add()' - 缺少什麼? – slim
另請注意,如果您使用Java 8的java.time包中的類,那麼幾乎所有有關日期的內容都會更加容易。 – slim