Dart DateTime isBefore()
Syntax & Examples


Syntax of DateTime.isBefore()

The syntax of DateTime.isBefore() method is:

 bool isBefore(DateTime other) 

This isBefore() method of DateTime returns true if this occurs before other.

Parameters

ParameterOptional/RequiredDescription
otherrequiredthe DateTime object to compare to

Return Type

DateTime.isBefore() returns value of type bool.



✐ Examples

1 Check if the first date occurs before the second date

In this example,

  1. We create two DateTime objects, dt1 and dt2, representing different dates.
  2. We then use the isBefore() method on dt1 with dt2 as the argument.
  3. The method returns true since dt1 occurs before dt2.
  4. We print the result to standard output.

Dart Program

void main() {
  var dt1 = DateTime(2024, 5, 3);
  var dt2 = DateTime(2024, 5, 4);
  var result = dt1.isBefore(dt2);
  print(result);
}

Output

true

2 Check if the first date occurs before the second date when they are equal

In this example,

  1. We create two identical DateTime objects, dt1 and dt2, representing the same date.
  2. We then use the isBefore() method on dt1 with dt2 as the argument.
  3. The method returns false since dt1 does not occur before dt2.
  4. We print the result to standard output.

Dart Program

void main() {
  var dt1 = DateTime(2024, 5, 3);
  var dt2 = DateTime(2024, 5, 3);
  var result = dt1.isBefore(dt2);
  print(result);
}

Output

false

3 Check if the first date occurs before the second date when the first date is earlier

In this example,

  1. We create two DateTime objects, dt1 and dt2, representing different dates.
  2. We then use the isBefore() method on dt1 with dt2 as the argument.
  3. The method returns false since dt1 does not occur before dt2.
  4. We print the result to standard output.

Dart Program

void main() {
  var dt1 = DateTime(2024, 5, 3);
  var dt2 = DateTime(2024, 5, 2);
  var result = dt1.isBefore(dt2);
  print(result);
}

Output

false

Summary

In this Dart tutorial, we learned about isBefore() method of DateTime: the syntax and few working examples with output and detailed explanation for each example.