Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Calculate time until event from current time

Tags:

java

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.

like image 493
Rudy B Avatar asked Mar 16 '16 17:03

Rudy B


People also ask

How do you calculate duration in Java?

Find the time difference between two dates in milliseconds by using the method getTime() in Java as d2. getTime() – d1. getTime(). Use date-time mathematical formula to find the difference between two dates.

How do you subtract time in Java?

>minus(TemporalAmount amountTosubtract) minus() method of a LocalTime class used to returns a copy of this LocalTime with the specified amount subtracted to date-time.

Which string method is used to calculate date and time?

To convert a string to a Date/Time value, use DATETIMEVALUE() passing in a string in the format “YYYY-MM-DD HH:MM:SS”. This method returns the Date/Time value in GMT.

How do you check if a date is in the past Java?

1. Java 8 isBefore() First minus the current date and then uses isBefore() to check if a date is a certain period older than the current date.


2 Answers

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);
like image 86
dcsohl Avatar answered Nov 09 '22 16:11

dcsohl


tl;dr

ChronoUnit.DAYS.between( 
    Instant.parse( "2016-08-16T19:45:00Z" ).atZone( ZoneId.of( "Europe/Paris" ) ), 
    Instant.parse( "2016-08-23T12:34:00Z" ).atZone( ZoneId.of( "Europe/Paris" ) ) 
);

Define “days”

There are two ways to count a number of days. Your Question is not quite clear which you intended. This Answer shows example code for both ways.

  • Calendar-based days by date
    Apply the intended time zone to determine the dates of the start and the the stop. A date is determined by zone, as for any given moment the date varies around the globe being “tomorrow” towards the east while “yesterday” to the west depending where you sit. For example a few minutes after midnight in Paris France a new day while still “yesterday” in Montréal Québec.
  • 24-hour chunks of time
    If you consider only generic days of 24-hour chunks of time while ignoring anomalies such as Daylight Saving Time (DST), then you get the total number of seconds between the beginning and ending moment and divide that by 24-hours. In this approach we ignore the calendar and its dates.

Example of the differences: Start late Monday night, an hour before midnight. Stop an hour after midnight on Wednesday morning. For 24-hour chunks that total of 26 hours is a single day. But by calendar dates that would two elapsed days, having touched three calendar days.

Why two days if we touched three? Date-time work commonly uses the Half-Open approach where the beginning is inclusive while the ending is exclusive.

Avoid legacy date-time classes

The modern way to do this work is with the java.time classes rather than the troublesome old legacy date-time classes (Date, Calendar, etc.).

The Answer by dcsohl is correct but could be shorter. No need to be explicit about the DateTimeFormatter as the input string is in one of the standard ISO 8601 formats used by default.

I know the string format of it is "yyyy-M-dd'T'h:m:s'Z'"

As part of the ISO 8601 standard, the Z on the end is short for Zulu and means UTC.

String startInput = "2016-08-16T19:45:00Z" ;
String stopInput = "2016-08-23T12:34:00Z" ;

Parse as Instant objects. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant start = Instant.parse( startInput );
Instant stop = Instant.parse( stopInput );

I know the timezone is "CET".

Time zone is irrelevant to parsing the strings. But time zone does matter in terms of calculating elapsed days if counting by calendar dates rather than by 24-hours per generic day.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST or CET as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "Europe/Paris" );

Adjust both our start and stop moments into that time zone.

ZonedDateTime zdtStart = start.atZone( z );
ZonedDateTime zdtStop = stop.atZone( z );

The java.time framework provides two classes for spans of time:

  • Period for years-months-days
  • Duration for hours-minutes-seconds

The Period class takes a pair of LocalDate objects, date-only values without time-of-day and without time zone. We can extract LocalDate objecs from our ZonedDateTime objects. Remember that date is determined by zone. So it is crucial that we adjusted our UTC values into ZonedDateTime objects.

Period p = Period.between( zdtStart.toLocalDate() , zdtStop.toLocalDate() );

You can interrogate that Period for the number of years and months and days of that span of time.

If you want a total number of days, use the ChronoUnit enum.

long days = ChronoUnit.DAYS.between( zdtStart , zdtStop );

The above is for calendar date-based counting of days.

If you want to count by generic chuncks of 24-hour periods, use the Duration class as shown in the Answer by dcsohl.

Duration.between( start , stop ).toDays()

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

  • Java SE 8, Java SE 9, Java SE 10, and later
    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and Java SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • Later versions of Android bundle implementations of the java.time classes.
    • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

like image 43
Basil Bourque Avatar answered Nov 09 '22 17:11

Basil Bourque