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
| Parameter | Optional/Required | Description |
|---|---|---|
other | required | the 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,
- We create two DateTime objects,
dt1anddt2, representing different dates. - We then use the
isBefore()method ondt1withdt2as the argument. - The method returns
truesincedt1occurs beforedt2. - 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,
- We create two identical DateTime objects,
dt1anddt2, representing the same date. - We then use the
isBefore()method ondt1withdt2as the argument. - The method returns
falsesincedt1does not occur beforedt2. - 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,
- We create two DateTime objects,
dt1anddt2, representing different dates. - We then use the
isBefore()method ondt1withdt2as the argument. - The method returns
falsesincedt1does not occur beforedt2. - 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.