2012-02-27 81 views
-1

我有一個int的值並且從int的值我想獲得Date對象的那個值爲int的值。從java的int值中獲取Date對象

實施例:

int value = 166368; 
long l = (long)value; 
Date date = new Date(l); 

價值是指欲用於此特定值Date對象我的整數值。

現在我想獲得Dateint值。我嘗試將此int值轉換爲long,然後在Date對象中設置long值,但它不返回正確的值。

那麼如何實現這一目標呢?

+6

你是什麼意思它不返回正確的值,何日你所期望的價值'166368'來表示? – ggreiner 2012-02-27 16:58:02

回答

1

如果您傳遞的長時間值是自紀元(1970年1月1日)以來的毫秒數,並且166368毫秒= 166.3秒,那麼我應該將1970年1月1日作爲日期值。正確?

2

您傳遞給Date構造函數的值必須是已通過自1970年以來00年1月1日的毫秒數:00:00.000 GMT。

您的代碼是正確的,但是您在此處傳遞的值似乎太小而無法正確。

0

@ggreiner指出,你應該告訴我們,你期望從int值166368得到哪個日期?

你的問題 「從int值獲取Date對象中的Java」 是可能的:

final int x = Integer.MAX_VALUE; 
final Date d = new Date(x); 
final Date today = new Date(); 
System.out.println("max integer x:" + x); 
System.out.println("the Max date could be represented by x:" + d); 
System.out.println("today in number:" + today.getTime()); 

運行上面的代碼,你有:

max integer x:2147483647 
the Max date could be represented by x:Sun Jan 25 21:31:23 CET 1970 
today in number:1330362276028 

這意味着,如果你傳遞給整日期()構造函數,它的工作原理,但你不會得到日期晚於Sun Jan 25 21:31:23 CET 1970

0

如果檢查API public Date(long date)做到這一點

分配Date對象並初始化,以表示自從稱爲「 時代」標準基準時間指定的毫秒 數,即1月1日,格林威治標準時間1970年00:00:00。

166368幾乎是3分鐘,所以日期不會改變。如果您打印,只會在時間上發現差異。

可能是你正在嘗試做這樣的事情

Date now = new Date(); 
long nowLong = now.getTime(); 
long newLong = nowLong + 166368; 
System.out.println(new Date(newLong).toString()); 

的日期玩是使用DateFormat類整潔的方式。

DateFormat df = new SimpleDateFormat(「dd/MM/yy」); String formattedDate = df。格式(新日期());

有一個詳細的文章here