2012-08-02 92 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));