2017-08-18 43 views
-4

给人错误的日期我见过SimpleDateFormat的android系统

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

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

+1

FYI,麻烦的老的日期 - 时间类,如['java.util.Date'](https://docs.oracle.com/javase/8/docs/api/java/util/Date .html),['java.util.Calendar'](https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html)和'java.text.SimpleTextFormat'现在[遗留](https://en.wikipedia.org/wiki/Legacy_system),由[java.time]代替(https://docs.oracle.com/javase/8/docs/api/java/time /package-summary.html)类。请参见[Oracle教程](https://docs.oracle.com/javase/tutorial/datetime/TOC.html)。 –

+1

感谢@BasilBourque,我不知道。我会看到教程:) – mrid

回答

1

您当前拥有的时间戳对于Android而言可以。事实上,您需要将其乘以1000才能在www.epochconverter.com上运行,这表明epochconverter使用不同的格式。只需在Date中扔leadTime,你应该没问题。

+1

时间戳以毫秒为单位,OP的标记以毫秒为单位。无论如何,* 1000的结论不是必需的。 – laalto

+0

@laalto。好的,我会更新它。我一直认为这是秒。我以为epochconverter.com(链接的网站)使用毫秒 – 0xDEADC0DE

+0

它现在正在工作!谢谢:) – mrid

0

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

2

其他答案是正确的关于不需要乘以千分之一,因为你已经有一个以毫秒为单位的数字。

避免遗留日期时类

但其他的答案和问题都使用麻烦的类,现在是遗产,由java.time类取代。见Oracle Tutorial

java.time

对于Android,看到ThreeTen,反向移植和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) ;