使用Joda Time将Unix时间戳转换为String

尝试将Unix timstamp从数据库转换为日期格式的String时。

int _startTS = evtResult.getInt("start"); //outputs 1345867200 Long _sLong = new Long(_startTS); //outputs 1345867200 //I've also tried: Long _sLong = new Long(_startTS*1000); //outputs 1542436352 DateTime _startDate = new DateTime(_sLong); //outputs 1970-01-16T08:51:07.200-05:00 

时间戳是: Sat, 25 Aug 2012 。 我不知道为什么1970年总是输出,所以希望有人可以看到我正在犯的一个愚蠢的错误。

Unix时间以秒为单位,Java时间为毫秒

你需要将它加倍1000

 DateTime _startDate = new DateTime(_sLong * 1000L); 

您可能想要查看此答案

Unix时间戳是自1970-01-01 00:00:00以来的一些SECONDS

DateTime(long instant)构造函数需要MILLISECONDS的数量。

 long _startTS = ((long) evtResult.getInt( "start" )) * 1000; DateTime _startDate = new DateTime( _startTS ); 

编辑:或者在你的evtResult上使用getLong(..)方法来避免evtResult转换。

执行此操作时: _startTS*1000 ,Java假定您需要一个int,因为_startTS是一个int(这就是为什么值为1542436352)。 试着把它作为一个很长的第一个:

 Long _sLong = new Long(((long)_startTS)*1000);