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

Convert timestamp in milliseconds to string formatted time in Java

我正在尝试将一个长值(从1970年1月1日起经过的毫秒数,即epoch)转换为h:m:s:ms格式的时间。

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

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

1
2
logEvent.timeStamp/ (1000*60*60)
TimeUnit.MILLISECONDS.toMinutes(logEvent.timeStamp)

但我得到的值不正确:

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

我该怎么办?


试试这个:

1
2
3
4
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的可运行示例。


1
2
3
4
5
6
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);


我将向您展示三种方法:(a)从长值中获取分钟字段;(b)使用所需的日期格式打印该字段。一个使用JavaUTL日历,另一个使用JoDA时间,最后使用JavaTime框架内置到Java 8和更高版本中。

java.time框架取代了旧的捆绑日期时间类,它受到jsr 310定义的joda time的启发,并由threeten额外项目扩展。

JavaTimeFrand是使用Java 8和以后的方法。否则,如android,使用joda time。Java.UTI.Deal/NoalCalm类是众所周知的麻烦,应该避免使用。

java.util.date&;日历

1
2
3
4
5
6
7
8
9
10
11
12
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);

乔达时间

1
2
3
4
5
6
7
8
// 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时间

1
2
3
4
5
6
7
8
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 );

millisecondsSinceEpoch: 1289375173771 instant: 2010-11-10T07:46:13.771Z output: 07:46:13:771


可以使用ApacheCommons(commons-lang3)及其durationFormatUtils类。

1
2
3
4
5
<dependency>
  <groupId>org.apache.commons</groupId>
  commons-lang3</artifactId>
  <version>3.1</version>
</dependency>

例如:

1
2
3
4
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"

希望能有帮助…


1
2
3
4
5
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);


1
2
3
4
5
6
7
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);


试试这个:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
    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);


1
logEvent.timeStamp / (1000*60*60)

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

1
logEvent.timeStamp / (1000*60)

最终你会得到和

1
TimeUnit.MILLISECONDS.toMinutes(logEvent.timeStamp)


1
2
3
4
5
6
7
    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);