Converting Unix timestamp to String with Joda Time

我的未来我决定 提交于 2019-12-05 08:55:44

问题


When trying to convert a Unix timstamp, from a database, to a String in a date format.

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

The timestamp is for: Sat, 25 Aug 2012. I have no idea why 1970 is always the output so hopefully someone can see a stupid mistake I'm making.


回答1:


Unix time is in seconds, Java time is milliseconds

You'll need to multiple it by 1000

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

You may want to check this answer out




回答2:


Unix time stamp is a number of SECONDS since 1970-01-01 00:00:00.

DateTime(long instant) constructor needs number of MILLISECONDS.

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

EDIT: or use getLong(..) method on your evtResult to avoid the cast to long.




回答3:


When you do this: _startTS*1000, Java assumes you want an int because _startTS is an int (that's why the value is 1542436352). Try casting it as a long first:

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


来源:https://stackoverflow.com/questions/12031333/converting-unix-timestamp-to-string-with-joda-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!