从长期转换为日期格式

HaO*_*aOx 30 android date long-integer

我想以这种格式dd/mm/YYYY将Long值转换为String或Date.

我有Long格式的这个值:1343805819061.

可以将其转换为日期格式吗?

AAn*_*kit 76

您可以使用以下代码行来执行此操作.这里timeInMilliSecond是长值.

 String dateString = new SimpleDateFormat("MM/dd/yyyy").format(new Date(TimeinMilliSeccond));
Run Code Online (Sandbox Code Playgroud)

或者你也可以使用下面的代码.

 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();
Run Code Online (Sandbox Code Playgroud)

参考: - DateFormatSimpleDateFormat

PS根据您的需要更改日期格式.

  • 补充一下,如果您还从中获取 1970 年的日期,请确保您的时间戳以毫秒为单位。近年来的日期时间戳应包含 13 位数字。我在这个问题上遇到了很多困难,因为我的数字有 10 位。 (2认同)

Mar*_*ker 5

您可以在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
Run Code Online (Sandbox Code Playgroud)

然后使用简单的日期格式化程序

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