Метод Instant isBefore () в Java с примерами

Опубликовано: 10 Февраля, 2022

isBefore () класса Instant проверяет, находится ли текущая позиция на временной шкале перед моментом, переданным в качестве параметра, или нет. Если это мгновенное положение на шкале времени до момента, переданного в качестве параметра, тогда метод вернет true, иначе false. Сравнение основано на положении моментов на шкале времени.

Синтаксис:

публичное логическое значение isBefore (Instant otherInstant)

Параметр: этот метод принимает параметр otherInstant, который является другим моментом для сравнения. Он не должен быть нулевым.

Returns: этот метод возвращает истину, если этот момент предшествует указанному моменту.

Исключение: этот метод выдает исключение NullPointerException, если otherInstant имеет значение null.

Ниже программы иллюстрируют метод isBefore ():

Program 1:

// Java program to demonstrate
// Instant.isBefore() method
  
import java.time.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create a Instant object
        Instant instant1
            = Instant.parse("2018-12-30T09:24:54.63Z");
  
        // create other Instant
        Instant instant2
            = Instant.parse("2018-12-31T01:34:00.63Z");
  
        // print instances
        System.out.println("Instance 1: " + instant1);
        System.out.println("Instance 2: " + instant2);
  
        // check if instant1 is after instant2
        // using isAfter()
        boolean value = instant1.isBefore(instant2);
  
        // print result
        System.out.println("Is Instant1 before Instant2: "
                           + value);
    }
}
Output:
Instance 1: 2018-12-30T09:24:54.630Z
Instance 2: 2018-12-31T01:34:00.630Z
Is Instant1 before Instant2: true

Program 2:

// Java program to demonstrate
// Instant.isBefore() method
  
import java.time.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create a Instant object
        Instant instant1
            = Instant.parse("2018-11-27T09:24:54.63Z");
  
        // create other Instant
        Instant instant2 = Instant.now();
  
        // print instances
        System.out.println("Instance 1: " + instant1);
        System.out.println("Instance 2: " + instant2);
  
        // check if instant1 is after instant2
        // using isAfter()
        boolean value = instant1.isBefore(instant2);
  
        // print result
        System.out.println("Is Instant1 before Instant2: "
                           + value);
    }
}
Output:
Instance 1: 2018-11-27T09:24:54.630Z
Instance 2: 2018-11-27T04:55:36.127Z
Is Instant1 before Instant2: false

Program 3: To show Exception thrown by isBefore()

// Java program to demonstrate
// Instant.isBefore() method
  
import java.time.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create a Instant object
        Instant instant1 = Instant.parse("2018-10-30T19:34:50.63Z");
  
        // create other Instant
        Instant instant2 = null;
  
        try {
  
            // print instances
            System.out.println("Instance 1: " + instant1);
            System.out.println("Instance 2: " + instant2);
  
            // check if instant1 is after instant2
            // using isAfter()
            boolean value = instant1.isBefore(instant2);
        }
        catch (Exception e) {
            // print result
            System.out.println("Exception: " + e);
        }
    }
}
Output:
Instance 1: 2018-10-30T19:34:50.630Z
Instance 2: null
Exception: java.lang.NullPointerException

Ссылки: https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#isBefore(java.time.Instant)

Вниманию читателя! Не переставай учиться сейчас. Ознакомьтесь со всеми важными концепциями Java Foundation и коллекций с помощью курса "Основы Java и Java Collections" по доступной для студентов цене и будьте готовы к работе в отрасли. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .