簡體   English   中英

如何在不使用SimpleDateFormat或Calendar的情況下獲取比當前日期早一年的java.util.Date

[英]How to get a java.util.Date which is a year back than the current date without using SimpleDateFormat or Calendar

我有當前日期,我想僅使用java.util.Date來獲取1年以前的日期

我在gwt中工作,所以不能使用SimpleDateFormatCalendar

Date currentDate = new Date();
Date oneYearBefore = new Date( - (365 * 24 * 60 * 60 * 1000));

上面提到的代碼不起作用(從某些論壇獲得了它)

使用日歷類

Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.YEAR, -1);
System.out.println(calendar.getTime());

為什么不能使用日歷? 我想您可能誤會了什么?

無論如何:

Date oneYearBefore = new Date( System.currentTimeMillis() - (365 * 24 * 60 * 60 * 1000));

或者使用您從論壇粘貼的代碼:

Date currentDate = new Date();
Date oneYearBefore = new Date( currentDate.getTime() - (365 * 24 * 60 * 60 * 1000));

僅使用java.util.Date ,您可以使用:

Date oneYearBefore = new Date(currentDate.getTime() - (365L * 24L * 60L * 60L * 1000L));

但是請記住,這並不代表潛在的leap年。

您正在使用所有int's ,將它們相乘會得到一個int。 您正在將int轉換為long,但是僅在int乘法已經導致錯誤的答案之后。 實際上它overflowing the int type

 public static void main(String[] args) {
        Date currentDate = new Date();
        System.out.println(currentDate);
        long milliseconds = (long) 365 * 24 * 60 * 60 * 1000;
        Date oneYearBefore = new Date(currentDate.getTime() - milliseconds);
        System.out.println(oneYearBefore);
    }

Mon Nov 17 13:11:10 IST 2014
Sun Nov 17 13:11:10 IST 2013

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM