将linux时间戳转换为android日期

时间:2014-08-02 16:57:39

标签: java android date

我必须将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

还有另一种方法可以获得正确的约会吗?

4 个答案:

答案 0 :(得分:3)

UNIX时间戳应以毫秒为单位,因此将Long值乘以1000.因此您的值1386889262将为1386889262000:

答案 1 :(得分:1)

如果您的UNIX时间戳是10位数字,则它不包括秒,因此请首先这样做1386889262 * 1000 如果它的13位数字还包括秒,则您不必将unix时间戳乘以1000。 在Kotlin中,我们可以使用以下功能:

val unix=1386889262*1000 /*if time stamp is of 10 digit*/
val dateFormat = SimpleDateFormat("dd-MM-yy HH:mm:ss");
val dt =  Date(unix);
textview.settext(dateFormat.format(dt))

答案 2 :(得分:0)

您的时间戳或纪元时间似乎在 sec “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();

返回一个长值。

答案 3 :(得分:0)

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 ) ; 

要生成代表此时刻的字符串,请致电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的堆栈溢出。

相关问题