在Java中将以毫秒为单位的时间戳转换为字符串格式的时间 [英] Convert timestamp in milliseconds to string formatted time in Java
本文介绍了在Java中将以毫秒为单位的时间戳转换为字符串格式的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将一个长值(从1970年1月1日经过的毫秒数,即Epoch )转换为格式为h:m:s:ms
的时间.
I am trying to convert a long value (number of milliseconds elapsed from 1/1/1970 i.e. Epoch) to time of format h:m:s:ms
.
用作时间戳的长值,我从log4j的日志记录事件的字段timestamp
中获得.
The long value I use as timestamp, I get from the field timestamp
of a logging event from log4j.
到目前为止,我已经尝试了以下操作,但失败了:
So far I've tried the following and it fails:
logEvent.timeStamp/ (1000*60*60)
TimeUnit.MILLISECONDS.toMinutes(logEvent.timeStamp)
但是我得到的值不正确:
but I get incorrect value:
1289375173771 for logEvent.timeStamp
358159 for logEvent.timeStamp/ (1000*60*60)
21489586 for TimeUnit.MILLISECONDS.toMinutes(logEvent.timeStamp)
我该怎么办?
推荐答案
尝试一下:
Date date = new Date(logEvent.timeSTamp);
DateFormat formatter = new SimpleDateFormat("HH:mm:ss.SSS");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateFormatted = formatter.format(date);
请参阅 SimpleDateFormat ,以获取有关以下内容的说明:该类接受的其他格式字符串.
See SimpleDateFormat for a description of other format strings that the class accepts.
使用1200毫秒的输入,参见可运行示例.
See runnable example using input of 1200 ms.
这篇关于在Java中将以毫秒为单位的时间戳转换为字符串格式的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文