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
Parameter | Optional/Required | Description |
---|---|---|
other | required | the 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,
- We create two DateTime instances,
date1
anddate2
, with the same year, month, day, hour, and minute. - We then use the
isAtSameMomentAs()
method to check ifdate1
occurs at the exact same moment asdate2
. - The method returns
true
if they are the same moment andfalse
otherwise. - 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,
- We create two DateTime instances,
date1
anddate2
, with different hours and minutes. - We then use the
isAtSameMomentAs()
method to check ifdate1
occurs at the exact same moment asdate2
. - The method returns
false
since the hours and minutes are different. - 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,
- We create two DateTime instances,
date1
anddate2
, with minute difference. - We then use the
isAtSameMomentAs()
method to check ifdate1
occurs at the exact same moment asdate2
. - The method returns
false
since the minutes are different, even though they are very close in time. - 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.