Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

Java Calculate time until event from current time

I am trying to calculate the amount of time until the start of a soccer game.

This is what I know:

  • I have the time of an event:2016-08-16T19:45:00Z
  • I know the string format of it is "yyyy-M-dd'T'h:m:s'Z'"
  • I know the timezone is "CET".

I want to be able to calculate the difference from the current time to this date in days.

This is what I have tried:

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Nobody has yet provided a Java 8 java.time answer...

    String eventStr = "2016-08-16T19:45:00Z";
    DateTimeFormatter fmt = DateTimeFormatter.ISO_ZONED_DATE_TIME;
    Instant event = fmt.parse(eventStr, Instant::from);
    Instant now = Instant.now();
    Duration diff = Duration.between(now, event);
    long days = diff.toDays();
    System.out.println(days);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...