Open In App

OffsetDateTime until() Method in Java with Examples

Last Updated : 22 Jan, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

until() method of the OffsetDateTime class used to calculate the amount of time between two OffsetDateTime objects using TemporalUnit. The start and end points are this and the specified OffsetDateTime passed as a parameter. The result will be negative if the end is before the start. The calculation returns a whole number, representing the number of complete units between the two OffsetDateTime. This instance is immutable and unaffected by this method call.

Syntax:

public long until(Temporal endExclusive, TemporalUnit unit)

Parameters: This method accepts two parameters endExclusive which is the end date, exclusive, which is converted to an OffsetDateTime and unit which is the unit to measure the amount.

Return value: This method returns the amount of time between this OffsetDateTime and the end OffsetDateTime.

Exception:This method throws following Exceptions:

  • DateTimeException – if the amount cannot be calculated, or the ending temporal cannot be converted to an OffsetDateTime.
  • UnsupportedTemporalTypeException – if the unit is not supported.
  • ArithmeticException – if numeric overflow occurs.

Below programs illustrate the until() method:
Program 1:




// Java program to demonstrate
// OffsetDateTime.until() method
  
import java.time.*;
import java.time.temporal.*;
  
public class GFG {
    public static void main(String[] args)
    {
        // create OffsetDateTime objects
        OffsetDateTime date1 = OffsetDateTime.parse("2018-12-12T13:30:30+05:00");
        OffsetDateTime date2 = OffsetDateTime.parse("2015-12-12T13:30:30+05:00");
  
        // apply until method of OffsetDateTime class
        long result
            = date2.until(date1,
                          ChronoUnit.MONTHS);
  
        // print results
        System.out.println("Result in MONTHS: "
                           + result);
    }
}


Output:

Result in MONTHS: 36

Program 2:




// Java program to demonstrate
// OffsetDateTime.until() method
  
import java.time.*;
import java.time.temporal.*;
  
public class GFG {
    public static void main(String[] args)
    {
        // create OffsetDateTime objects
        OffsetDateTime date1 = OffsetDateTime.parse("2018-12-12T13:30:30+05:00");
        OffsetDateTime date2 = OffsetDateTime.parse("2015-12-12T13:30:30+05:00");
  
        // apply until method of OffsetDateTime class
        long result
            = date1.until(date2,
                          ChronoUnit.YEARS);
  
        // print results
        System.out.println("Result in YEARS: "
                           + result);
    }
}


Output:

Result in YEARS: -3

References:
https://docs.oracle.com/javase/10/docs/api/java/time/OffsetDateTime.html#until(java.time.temporal.Temporal, java.time.temporal.TemporalUnit)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads