2011-06-07 73 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()); 
相关问题