2011-06-07 72 views
14

我需要檢索的一天年份和月份從時間戳對象,只要數字:如何檢索一天月份和年份的時間戳(長格式)

public long getTimeStampDay() 
    { 

      String iDate = new SimpleDateFormat("dd/MM/yyyy") 
     .format(new Date(born_date.getDate())); 
     ..... 

       return day; //just the day 

    } 

public long getTimeStampMonth() 
    { 
    String iDate = new SimpleDateFormat("dd/MM/yyyy") 
     .format(new Date(born_date.getDate())); 
     ..... 

       return month; //just month 

    } 

public long getTimeStampYear() 
    { 
    String iDate = new SimpleDateFormat("dd/MM/yyyy") 
     .format(new Date(born_date.getDate())); 
     ..... 

       return year; //just year 
    } 

born_date是時間戳對象。

有沒有可能這樣做?

在此先感謝。

回答

36
long timestamp = bornDate.getTime(); 
Calendar cal = Calendar.getInstance(); 
cal.setTimeInMillis(timestamp); 
return cal.get(Calendar.YEAR); 

每個屬性都有您需要的日曆字段。

或者您可以使用joda-time

DateTime dateTime = new DateTime(bornDate.getDate()); 
return datetime.getYear(); 
+0

你好,我的情況下,變量 「bornDate」 類型 「的java.sql.Timestamp」。 我想從「bornDate」中檢索一年。 「getYear()」被棄用,但「getDate()」也被棄用... 那麼,應該做什麼?謝謝。 – 2014-03-04 10:20:52

+0

「bornDate」類型是「java.sql.Timestamp」。 以下代碼可以做到這一點: Calendar calendar = Calendar.getInstance(); calendar.setTime(bornDate); System.out.println(calendar.get(Calendar.YEAR)); – 2014-03-04 10:24:50

0

鑑於要在每種方法使用日期格式,則可以在各自使用不同的格式串。例如:

public long getTimeStampDay() 
    { 

      String day = new SimpleDateFormat("dd") 
     .format(new Date(born_date.getDate())); 
     ..... 

       return Long.parseLong(day); //just the day 

    } 
-3

我發現了一個簡單的方法來做到這一點:

born_date.getDay(); 
born_date.getMonth(); 
born_date.getYear(); 

即使方法getDay得到月和得到年被棄用。 我認爲Bozho解決方案是最好的解決方案。

+1

'born_date.getDay()' - >自jdk 1.1開始已棄用。 getMonth()和getYear()同樣。使用@Bozho解決方案 – 1ac0 2013-08-05 18:59:01

+0

儘管此鏈接可能會回答問題,但最好在此處包含答案的重要部分,並提供供參考的鏈接。如果鏈接頁面更改,則僅鏈接答案可能會失效。 - [來自評論](/ review/low-quality-posts/12535761) – nullpointer 2016-06-01 07:03:19

+0

@nullpointer鏈接在哪裏? – 2016-06-01 08:12:13

-1

該方法返回的日子,日期,年份和時間:

Timestamp timestamp = new Timestamp(System.currentTimeMillis()); 
相關問題