Java用时间戳计算时间 [英] Java calculating time with timestamps

查看:1531
本文介绍了Java用时间戳计算时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图计算两个时间戳之间的时差,这是代码:

Im trying to calculate the time difference between 2 Timestamps, this is the code:

        Calendar calendar = Calendar.getInstance();
        java.util.Date now = calendar.getTime();
        Timestamp currentTimestamp = new Timestamp(now.getTime());
        System.out.println("Current\n"+currentTimestamp);

        DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
        Date date = dateFormat.parse("28/02/2015");
        Timestamp timestampBefore = new Timestamp(date.getTime());
        System.out.println("Before\n"+timestampBefore);

        Timestamp calculated = new Timestamp(currentTimestamp.getTime() - timestampBefore.getTime());
        System.out.println("Calculated\n"+calculated);

输出:

Current
2015-02-28 12:12:40.975
Before
2015-02-28 00:00:00.0
Calculated
1970-01-01 13:12:40.975




  1. 我能理解为什么返回 1970-01-01 ,但为什么返回 13:12:40.975 ,又多了1个小时?

  1. I can understand why it returns 1970-01-01 but why does it return 13:12:40.975 ,1 hour more?

如何计算两个日期之间的差,因此输出如下(基于此示例):

Years:0,月0 :,天:0,小时:12,分钟:12,秒:40?

How to calculate the difference between 2 dates so the output is like this (based on this example):
Years:0, Months:0, Days:0, Hours:12, Minutes:12, Seconds:40 ?

更新:对于1.8以下的Java,请查看> http://www.joda.org/joda-time/index.html

对于Java 1.8,请参见答案。

Update: for java below 1.8 check out http://www.joda.org/joda-time/index.html
and for java 1.8 see answer.

此处类似的解决方案: Java 8:计算两个LocalDateTime之间的差异

推荐答案

(1)时间戳是一个时间点。如果您计算两个时间戳之间的差,则结果不是时间戳(时间点),而是持续时间。因此,将差异转换为时间戳是没有意义的,因此讨论结果奇怪的原因是没有用的。

(1) A timestamp is a point in time. If you calculate the difference between two timestamps, the result is not a timestamp (point in time), but a duration. So it is nonsense to convert the difference to a timestamp, hence it is useless to discuss the reason why the result is strange.

(2)您可能应该使用新的 Java 8时间API (如果您能够使用Java 8):

(2) You should probably use the new Java 8 time API (if you are able to use Java 8):

LocalTime now = LocalTime.now();
LocalTime previous = LocalTime.of(0, 0, 0, 0);
Duration duration = Duration.between(previous, now);

System.out.println(now);
System.out.println(previous);
System.out.println(duration);

请注意,这只是计算一天两次(时分秒)之间的持续时间。如果要包括日期信息,请使用 LocalDateTime 代替:

Note that this just calculates the duration between two times of a day (hour-minute-second). If your want to include date information, use LocalDateTime instead:

LocalDateTime nextFirework = LocalDate.now()
                             .with(TemporalAdjusters.firstDayOfNextYear())
                             .atTime(LocalTime.MIDNIGHT);
LocalDateTime now = LocalDateTime.now();

// duration (in seconds and nanos)
Duration duration = Duration.between(now, nextFirework);
// duration in total hours
long hours = now.until(nextFirework, ChronoUnit.HOURS);
// equals to: duration.toHours();

如果要以年/月/日/小时/秒为单位的标准化持续时间,令人惊讶的是没有直接的支持。您可以自己将持续时间转换为天,小时,分钟和秒:

If you want to have 'normalized' duration in years/months/days/hours/seconds, there is suprisingly no direct support. You could convert the duration to days, hours, minutes and seconds by yourself:

long d = duration.toDays();
long h = duration.toHours() - 24 * d;
long m = duration.toMinutes() - 60 * duration.toHours();
long s = duration.getSeconds() - 60 * duration.toMinutes();
System.out.println(d + "d " + h + "h " + m + "m " + s + "s ");

但是请注意,由于没有唯一的数字,您将很难将日期转换成月和年每月和每年的天数可以是366天的a年。为此,您可以使用 Period ,与 Duration 相反,此类与时间轴关联。不幸的是,期间仅支持日期,但不支持日期:

But note that you will have difficulties converting the days into months and years, as there is no unique number of days per month and a year can be a leap year with 366 days. For that, you can use Period, as in opposite to Duration, this class is associated with a timeline. Unfortunately, Period does only support dates, but no times:

// period in years/months/days (ignoring time information)
Period p = Period.between(now.toLocalDate(), nextFirework.toLocalDate());
System.out.println(p); // or use p.getYears(), p.getMonths(), p.getDays()

因此,可能您可以结合使用这两种方法-首先,根据日期计算期限,然后根据时间计算持续时间。请注意,持续时间可以是负数,因此在以下情况下您必须加以注意:

So probably you could combine both approaches - first, compute the Period from the dates and then the Duration using the times. Note that the duration can be negative, so you'll have to take care of that in case of:

Duration dur = Duration.between(start.toLocalTime(), end.toLocalTime());
LocalDate e = end.toLocalDate();
if (dur.isNegative()) {
    dur = dur.plusDays(1);
    e = e.minusDays(1);
}
Period per = Period.between(start.toLocalDate(), e);
System.out.println(per.toString() + ", " + dur.toString());

这篇关于Java用时间戳计算时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆