java convert milliseconds to time format

2019-01-01 06:39发布

I am trying to convert a long value (The number of milliseconds elapsed from 1/1/1970) to a time of format h:m:s:ms
The long value I use as timestamp, I get from the field timestamp of logging event from log4j.
How do I do the conversion?
For example to get the minutes I tried the following and all fail:
logEvent.timeStamp/ (1000*60*60) and
TimeUnit.MILLISECONDS.toMinutes(logEvent.timeStamp)
but I get garbage:
I get

1289375173771 for logEvent.timeStamp
358159  for logEvent.timeStamp/ (1000*60*60) 
21489586 for TimeUnit.MILLISECONDS.toMinutes(logEvent.timeStamp)

How can I convert this?

Thanks

9条回答
路过你的时光
2楼-- · 2019-01-01 07:40
    long hours = TimeUnit.MILLISECONDS.toHours(timeInMilliseconds);
    long minutes = TimeUnit.MILLISECONDS.toMinutes(timeInMilliseconds - TimeUnit.HOURS.toMillis(hours));
    long seconds = TimeUnit.MILLISECONDS
            .toSeconds(timeInMilliseconds - TimeUnit.HOURS.toMillis(hours) - TimeUnit.MINUTES.toMillis(minutes));
    long milliseconds = timeInMilliseconds - TimeUnit.HOURS.toMillis(hours)
            - TimeUnit.MINUTES.toMillis(minutes) - TimeUnit.SECONDS.toMillis(seconds);
    return String.format("%02d:%02d:%02d:%d", hours, minutes, seconds, milliseconds);
查看更多
怪性笑人.
3楼-- · 2019-01-01 07:41

It is possible to use apache commons (commons-lang3) and its DurationFormatUtils class.

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.1</version>
</dependency>

For example:

String formattedDuration = DurationFormatUtils.formatDurationHMS(12313152);
// formattedDuration value is "3:25:13.152"
String otherFormattedDuration = DurationFormatUtils.formatDuration(12313152, DurationFormatUtils.ISO_EXTENDED_FORMAT_PATTERN);
// otherFormattedDuration value is "P0000Y0M0DT3H25M13.152S"

Hope it can help ...

查看更多
笑指拈花
4楼-- · 2019-01-01 07:43

Try this:

Date date = new Date(logEvent.timeSTamp);
DateFormat formatter = new SimpleDateFormat("HH:mm:ss.SSS");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateFormatted = formatter.format(date);

See SimpleDateFormat for a description of other format strings that the class accepts.

See runnable example using input of 1200 ms.

查看更多
登录 后发表回答