2012-08-02 86 views
18

我想將長值轉換爲字符串或日期,格式爲dd/mm/YYYY。從長轉換爲日期格式

我在長格式此值:1343805819061.

有可能將其轉換爲日期格式?

謝謝。

回答

51

您可以使用下面的代碼行來做到這一點。這裏timeInMilliSecond是長整型值。

String dateString = new SimpleDateFormat("MM/dd/yyyy").format(new Date(TimeinMilliSeccond)); 

或者你也可以使用下面的代碼。

String longV = "1343805819061"; 
long millisecond = Long.parseLong(longV); 
// or you already have long value of date, use this instead of milliseconds variable. 
String dateString = DateFormat.format("MM/dd/yyyy", new Date(millisecond)).toString(); 

參考: - DateFormatSimpleDateFormat

附:根據您的需要更改日期格式。

4

您可以在Date實例或構造函數Date(long)上使用方法setTime;

setTime(long time) 
     Sets this Date object to represent a point in time that is time milliseconds after January 1, 1970 00:00:00 GMT. 

Date(long date) 
     Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT 

然後用簡單的日期格式化器

http://docs.oracle.com/javase/1.4.2/docs/api/javax/swing/text/DateFormatter.html

2
java.util.Date dateObj = new java.util.Date(timeStamp); 

這裏的timeStamp是你的長整型這實際上是時間戳millieseconds, 你獲取Java日期對象,現在你可以通過這個將它轉換成字符串

SimpleDateFormat dateformatYYYYMMDD = new SimpleDateFormat("yyyyMMdd"); 
SimpleDateFormat dateformatMMDDYYYY = new SimpleDateFormat("MMddyyyy"); 

StringBuilder nowYYYYMMDD = new StringBuilder(dateformatYYYYMMDD.format(dateObj)); 
StringBuilder nowMMDDYYYY = new StringBuilder(dateformatMMDDYYYY.format(dateObj));