SimpleDateFormat在android

时间:2017-08-18 09:58:51

标签: java android date datetime

我见过

  

Convert from UNIX Timestamp to "Today at: currentTime" using Java

     

Convert unix time stamp to date in java

但这些都不适合我。

我有一个时间戳:1503037706145

我正在使用以下代码将其转换为可读日期:

Long leadTime = leadData.getLong("addedOn");

Date date = new Date(leadTime*1000);
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy  |  hh:mm a");
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
String formattedDate = sdf.format(date);

它正在返回15/05/49599 11:25:45PM

但是当我在this上查看时,会返回Friday, 18 August 2017 07:00:14.817

这是正确的。我做错了什么?

3 个答案:

答案 0 :(得分:2)

其他答案是正确的,不需要将你的count-from-epoch乘以一千,因为你已经有一个以毫秒为单位的数字。

避免遗留日期时间类

但是其他的答案和问题都使用了现在遗留下来的麻烦的类,取而代之的是java.time类。请参阅Oracle Tutorial

java.time

对于Android,请参阅ThreeTen-Backport和ThreeTenABP项目。

Instant是UTC的时间轴上的一个时刻,解析为纳秒。

Instant instant = Instant.ofEpochMilli( 1503037706145 ) ;  // Instant is a moment on timeline in UTC resolved to nanoseconds.
String output = instant.toString() ;  // Generate string in standard ISO 8601 format. 

根据需要指定时区。

ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;

答案 1 :(得分:1)

您目前拥有的时间戳适用于Android。您需要将其乘以1000以使其在www.epochconverter.com上运行,这表明epochconverter使用不同的格式。只需在日期中抛出leadTime,你就可以了。

答案 2 :(得分:0)

我建议使用obj,因为某些版本的Android不支持DateFormat.format("MMM dd, hh:mm a", timeInMillisec * 1000)

相关问题