Java计算从当前时间到事件的时间 [英] Java Calculate time until event from current time
本文介绍了Java计算从当前时间到事件的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在计算足球比赛开始前的时间。
I am trying to calculate the amount of time until the start of a soccer game.
这就是我所知道的:
- 我有时间参加活动: 2016-08-16T19:45:00Z
- 我知道它的字符串格式为 yyyy-M-dd'T'h:m:s'Z'
- 我知道时区是CET 。
我希望能够计算从当前时间到此日期的差异。
I want to be able to calculate the difference from the current time to this date in days.
这就是我的尝试:
String gameDate = "2016-03-19T19:45:00'Z'"
DateFormat apiFormat = new SimpleDateFormat("yyyy-M-dd'T'h:m:s'Z'");
apiFormat.setTimeZone(TimeZone.getTimeZone("CET"));
Date dateOfGame = apiFormat.parse(gameDate);
DateFormat currentDateFormat = new SimpleDateFormat("yyyy-M-dd'T'h:m:s'Z'");
currentDateFormat.setTimeZone(TimeZone.getTimeZone(userTimezone));
Date currentDate = apiFormat.parse(currentDateFormat.format(new Date()));
long lGameDate = dateOfGame.getTime();
long lcurrDate = currentDate.getTime();
long difference = lGameDate - lcurrDate;
Date timeDifference = new Date(difference);
String daysAway = new SimpleDateFormat("d").format(timeDifference);
Integer intDaysAway = Integer.parseInt(daysAway);
你可能想知道为什么我不只是得到游戏的日期(8)并减去当前日期(19)。我不会在当前日期为29日,游戏日期是下个月的第3天的边缘情况下这样做。
You are probably wondering why I don't just get the date of the game (8) and subtract the current date (19). I don't do that in the edge case that the current date is the 29th and the game date is the 3rd of the next month.
推荐答案
尝试使用 TimeUnit
:
final String gameDate = "2016-03-19T19:45:00Z";
final SimpleDateFormat apiFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
apiFormat.setTimeZone(TimeZone.getTimeZone("CET"));
final Date dateOfGame = apiFormat.parse(gameDate);
final long millis = dateOfGame.getTime() - System.currentTimeMillis();
System.out.println(dateOfGame.getTime() - System.currentTimeMillis());
final String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
System.out.println(hms);
这将打印输出:
72:57:34
72:57:34
从现在起72小时57分34秒直到gameDate
72 hours, 57 minutes and 34 seconds from now until gameDate
这篇关于Java计算从当前时间到事件的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文