141

我正在尝试将 long 值(从 1970 年 1 月 1 日即 Epoch 所经过的毫秒数)转换为格式时间h:m:s:ms

我用作时间戳的长值,我timestamp从 log4j 的日志记录事件的字段中获得。

到目前为止,我已经尝试了以下方法,但失败了:

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)

我该怎么做?

4

10 回答 10

201

尝试这个:

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 。

请参阅使用 1200 ms 输入的可运行示例。

于 2010-11-10T08:12:05.897 回答
147
long millis = durationInMillis % 1000;
long second = (durationInMillis / 1000) % 60;
long minute = (durationInMillis / (1000 * 60)) % 60;
long hour = (durationInMillis / (1000 * 60 * 60)) % 24;

String time = String.format("%02d:%02d:%02d.%d", hour, minute, second, millis);
于 2013-05-13T11:26:34.627 回答
41

我将向您展示三种方法来 (a) 从 long 值中获取分钟字段,以及 (b) 使用所需的日期格式打印它。一个使用java.util.Calendar,另一个使用Joda-Time,最后一个使用 Java 8 及更高版本中内置的 java.time 框架。

java.time 框架取代了旧的捆绑日期时间类,并受到 JSR 310 定义并由 ThreeTen-Extra 项目扩展的 Joda-Time 的启发。

java.time 框架是使用 Java 8 及更高版本时要走的路。否则,例如 Android,请使用 Joda-Time。java.util.Date/.Calendar 类是出了名的麻烦,应该避免。

java.util.Date & .Calendar

final long timestamp = new Date().getTime();

// with java.util.Date/Calendar api
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timestamp);
// here's how to get the minutes
final int minutes = cal.get(Calendar.MINUTE);
// and here's how to get the String representation
final String timeString =
    new SimpleDateFormat("HH:mm:ss:SSS").format(cal.getTime());
System.out.println(minutes);
System.out.println(timeString);

乔达时间

// with JodaTime 2.4
final DateTime dt = new DateTime(timestamp);
// here's how to get the minutes
final int minutes2 = dt.getMinuteOfHour();
// and here's how to get the String representation
final String timeString2 = dt.toString("HH:mm:ss:SSS");
System.out.println(minutes2);
System.out.println(timeString2);

输出:

24
09:24:10:254
24
09:24:10:254

java.time

long millisecondsSinceEpoch = 1289375173771L;
Instant instant = Instant.ofEpochMilli ( millisecondsSinceEpoch );
ZonedDateTime zdt = ZonedDateTime.ofInstant ( instant , ZoneOffset.UTC );

DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "HH:mm:ss:SSS" );
String output = formatter.format ( zdt );

System.out.println ( "millisecondsSinceEpoch: " + millisecondsSinceEpoch + " instant: " + instant + " output: " + output );

毫秒SinceEpoch:1289375173771 瞬间:2010-11-10T07:46:13.771Z 输出:07:46:13:771

于 2010-11-10T08:16:03.650 回答
22

可以使用 apache commons (commons-lang3) 及其 DurationFormatUtils 类。

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

例如:

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"

希望它可以帮助...

于 2014-02-27T14:49:58.783 回答
8
long second = TimeUnit.MILLISECONDS.toSeconds(millis);
long minute = TimeUnit.MILLISECONDS.toMinutes(millis);
long hour = TimeUnit.MILLISECONDS.toHours(millis);
millis -= TimeUnit.SECONDS.toMillis(second);
return String.format("%02d:%02d:%02d:%d", hour, minute, second, millis);
于 2014-05-22T16:42:42.120 回答
6
public static String timeDifference(long timeDifference1) {
long timeDifference = timeDifference1/1000;
int h = (int) (timeDifference / (3600));
int m = (int) ((timeDifference - (h * 3600)) / 60);
int s = (int) (timeDifference - (h * 3600) - m * 60);

return String.format("%02d:%02d:%02d", h,m,s);
于 2015-01-21T04:27:12.730 回答
5

尝试这个:

    String sMillis = "10997195233";
    double dMillis = 0;

    int days = 0;
    int hours = 0;
    int minutes = 0;
    int seconds = 0;
    int millis = 0;

    String sTime;

    try {
        dMillis = Double.parseDouble(sMillis);
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }


    seconds = (int)(dMillis / 1000) % 60;
    millis = (int)(dMillis % 1000);

    if (seconds > 0) {
        minutes = (int)(dMillis / 1000 / 60) % 60;
        if (minutes > 0) {
            hours = (int)(dMillis / 1000 / 60 / 60) % 24;
            if (hours > 0) {
                days = (int)(dMillis / 1000 / 60 / 60 / 24);
                if (days > 0) {
                    sTime = days + " days " + hours + " hours " + minutes + " min " + seconds + " sec " + millis + " millisec";
                } else {
                    sTime = hours + " hours " + minutes + " min " + seconds + " sec " + millis + " millisec";
                }
            } else {
                sTime = minutes + " min " + seconds + " sec " + millis + " millisec";
            }
        } else {
            sTime = seconds + " sec " + millis + " millisec";
        }
    } else {
        sTime = dMillis + " millisec";
    }

    System.out.println("time: " + sTime);
于 2015-09-07T05:22:28.403 回答
4

正在做

logEvent.timeStamp / (1000*60*60)

会给你几个小时,而不是几分钟。尝试:

logEvent.timeStamp / (1000*60)

你最终会得到相同的答案

TimeUnit.MILLISECONDS.toMinutes(logEvent.timeStamp)
于 2010-11-10T08:06:09.830 回答
1
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);
于 2018-12-07T23:06:20.620 回答
0

我只想显示时间的相关部分。所以,总是显示秒,但如果有的话,只显示分钟/小时/天。

此外,可选择显示毫秒。

而且我使用的是 GWT,所以我不能使用 String.format。

所以,如果这也是你,这里是代码。

public static String formatTimeFromMs(long timeInMs, boolean showMs) {
    boolean negative = timeInMs < 0;

    timeInMs = Math.abs(timeInMs);

    StringBuffer result = new StringBuffer();
    long seconds = (timeInMs / 1000) % 60;
    long minutes = (timeInMs / (1000 * 60)) % 60;
    long hours = (timeInMs / (1000 * 60 * 60)) % 24;
    long days = (timeInMs / (1000 * 60 * 60 * 24));

    if (days > 0) {
        result.append(days + "d ");
    }
    
    if (hours > 0) {
        if (hours < 10 && result.length() > 0) {
            result.append("0");
        }
        result.append(hours + ":");
    }
    else if (result.length() > 0) {
        result.append("00:");
    }

    if (minutes > 0) {
        if (minutes < 10 && result.length() > 0) {
            result.append("0");
        }
        result.append(minutes + ":");
    }
    else if (result.length() > 0) {
        result.append("00:");
    }

    if (seconds > 0) {
        if (seconds < 10 && result.length() > 0) {
            result.append("0");
        }
        result.append(seconds);
    }
    else if (result.length() > 0) {
        result.append("00");
    }
    else {
        result.append("0");
    }

    if (showMs) {
        long millis = timeInMs % 1000;
        
        if (millis < 10) {
            result.append(".00" + millis);
        }
        else if (millis < 100) {
            result.append(".0" + millis);
        }
        else {
            result.append("." + millis);
        }
    }

    if (negative) {
        result.insert(0, "-");
    }

    return result.toString();
}
于 2021-08-12T05:38:53.593 回答