Dart DateTime isAtSameMomentAs()
Syntax & Examples


Syntax of DateTime.isAtSameMomentAs()

The syntax of DateTime.isAtSameMomentAs() method is:

 bool isAtSameMomentAs(DateTime other) 

This isAtSameMomentAs() method of DateTime returns true if this occurs at the same moment as other.

Parameters

ParameterOptional/RequiredDescription
otherrequiredthe DateTime instance to compare with this DateTime

Return Type

DateTime.isAtSameMomentAs() returns value of type bool.



✐ Examples

1 Check if two DateTime instances represent the same moment

In this example,

  1. We create two DateTime instances, date1 and date2, with the same year, month, day, hour, and minute.
  2. We then use the isAtSameMomentAs() method to check if date1 occurs at the exact same moment as date2.
  3. The method returns true if they are the same moment and false otherwise.
  4. We print the result to standard output.

Dart Program

void main() {
  DateTime date1 = DateTime(2023, 5, 1, 10, 30);
  DateTime date2 = DateTime(2023, 5, 1, 10, 30);
  bool isSameMoment = date1.isAtSameMomentAs(date2);
  print('Are date1 and date2 the same moment: $isSameMoment');
}

Output

Are date1 and date2 the same moment: true

2 Check if two DateTime instances represent different moments

In this example,

  1. We create two DateTime instances, date1 and date2, with different hours and minutes.
  2. We then use the isAtSameMomentAs() method to check if date1 occurs at the exact same moment as date2.
  3. The method returns false since the hours and minutes are different.
  4. We print the result to standard output.

Dart Program

void main() {
  DateTime date1 = DateTime(2023, 5, 1, 12, 0);
  DateTime date2 = DateTime(2023, 5, 1, 10, 30);
  bool isSameMoment = date1.isAtSameMomentAs(date2);
  print('Are date1 and date2 the same moment: $isSameMoment');
}

Output

Are date1 and date2 the same moment: false

3 Check if two DateTime instances represent slightly different moments

In this example,

  1. We create two DateTime instances, date1 and date2, with minute difference.
  2. We then use the isAtSameMomentAs() method to check if date1 occurs at the exact same moment as date2.
  3. The method returns false since the minutes are different, even though they are very close in time.
  4. We print the result to standard output.

Dart Program

void main() {
  DateTime date1 = DateTime(2023, 5, 1, 10, 30);
  DateTime date2 = DateTime(2023, 5, 1, 10, 29);
  bool isSameMoment = date1.isAtSameMomentAs(date2);
  print('Are date1 and date2 the same moment: $isSameMoment');
}

Output

Are date1 and date2 the same moment: false

Summary

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