java时间戳计算,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);

Output:

Current

2015-02-28 12:12:40.975

Before

2015-02-28 00:00:00.0

Calculated

1970-01-01 13:12:40.975

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

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 ?

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

and for java 1.8 see answer.

解决方案

(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) 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);

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 ");

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());

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值