将时间戳(以毫秒为单位)转换为 Java 中的字符串格式时间

Convert timestamp in milliseconds to string formatted time in Java(将时间戳(以毫秒为单位)转换为 Java 中的字符串格式时间)
本文介绍了将时间戳(以毫秒为单位)转换为 Java 中的字符串格式时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在尝试将一个 long 值(从 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)

但我得到的值不正确:

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 中的字符串格式时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)