Dart DateTime operator ==
Syntax & Examples


Syntax of DateTime.operator ==

The syntax of DateTime.operator == operator is:

operator ==(Object other) → bool

This operator == operator of DateTime returns true if other is a DateTime at the same moment and in the same time zone (UTC or local).

Parameters

ParameterOptional/RequiredDescription
otherrequiredthe object to compare with this DateTime instance


✐ Examples

1 Check equality of two DateTime instances

In this example,

  1. We create two DateTime instances, date1 and date2, with the same date.
  2. We then use the == operator to compare date1 and date2.
  3. Since both instances represent the same date, the equality check returns true.
  4. We print the result to standard output.

Dart Program

void main() {
  DateTime date1 = DateTime(2023, 5, 10);
  DateTime date2 = DateTime(2023, 5, 10);
  bool isEqual = date1 == date2;
  print('Dates are equal: $isEqual');
}

Output

Dates are equal: true

2 Check inequality of two DateTime instances

In this example,

  1. We create two DateTime instances, date1 and date2, with different dates.
  2. We then use the == operator to compare date1 and date2.
  3. Since the instances represent different dates, the equality check returns false.
  4. We print the result to standard output.

Dart Program

void main() {
  DateTime date1 = DateTime(2023, 5, 10);
  DateTime date2 = DateTime(2023, 5, 11);
  bool isEqual = date1 == date2;
  print('Dates are equal: $isEqual');
}

Output

Dates are equal: false

3 Check equality of two DateTime instances with the same date

In this example,

  1. We create two DateTime instances, date1 and date2, with the same date.
  2. We then use the == operator to compare date1 and date2.
  3. Since both instances represent the same date, the equality check returns true.
  4. We print the result to standard output.

Dart Program

void main() {
  DateTime date1 = DateTime(2023, 5, 10);
  DateTime date2 = DateTime(2023, 5, 10);
  bool isEqual = date1 == date2;
  print('Dates are equal: $isEqual');
}

Output

Dates are equal: true

Summary

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