将linux时间戳转换为android日期
我必须将linux时间戳转换为android日期。 我从服务器上得到这个号码
1386889262
我写了一个小代码片段。
Date d = new Date(jsonProductData.getLong(MTIME)); SimpleDateFormat f = new SimpleDateFormat("dd.MM.yyyy"); .setTimeZone(TimeZone.getTimeZone("GMT")); formatTime = f.format(d);
但它没有正确转换,这是我的结果
17.01.1970
编辑 :通常我必须在这里得到这个
12.12.2013
有没有另一种方法来获得正确的约会???
UNIX时间戳应该以毫秒为单位,因此将Long值乘以1000.因此您的值1386889262将为1386889262000:
您的时间戳或纪元时间似乎在秒 “1386889262”。 你必须做这样的事情:
long date1 = 1386889262*1000; SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yy HH:mm"); Date dt = new Date(date1); datedisplay.setText(dateFormat.format(dt));
您还可以通过java获取时间戳
new Date()。getTime();
它返回一个long值。
TL;博士
Instant.ofEpochSecond( 1386889262L ) .atZone( ZoneId.of( "Pacific/Auckland" ) ) .toLocalDate() .toString()
java.time
您似乎从UTC,1970-01-01T00:00:00Z的1970年第一时刻的纪元参考日期开始计算整秒。
现代方法使用java.time类来取代与最早版本的Java捆绑在一起的麻烦的旧日期时间类。 对于较旧的Android,请参阅ThreeTen- Backport和ThreeTenABP项目。
Instant
表示UTC时间轴上的一个点,分辨率为纳秒(小数部分最多为九位)。
Instant instant = Instant.ofEpochSecond( 1386889262L ) ;
要生成表示此时刻的String,请调用toString
。
String output = instant.toString() ;
确定日期需要时区。 对于任何给定的时刻,日期在全球范围内因地区而异。 分配ZoneId
以获取ZonedDateTime
对象。
ZoneId z = ZoneId.of( "Africa/Casablanca" ) ; ZonedDateTime zdt = instant.atZone( z ) ;
为您的目的提取仅限日期的值。
LocalDate ld = zdt.toLocalDate() ;
生成一个字符串。
String output = ld.toString() ;
对于String中的其他格式,请搜索DateTimeFormatter
Stack Overflow。