Dart DateTime hour
Syntax & Examples
Syntax of DateTime.hour
The syntax of DateTime.hour property is:
int hour
This hour property of DateTime the hour of the day, expressed as in a 24-hour clock [0..23]
.
Return Type
DateTime.hour returns value of type int
.
✐ Examples
1 Get current hour
In this example,
- We create a DateTime object
now
with the current date and time usingDateTime.now()
. - We then access the
hour
property ofnow
to get the current hour of the day. - We print the current hour to standard output.
Dart Program
void main() {
DateTime now = DateTime.now();
int currentHour = now.hour;
print('Current hour: $currentHour');
}
Output
Current hour: 21 (The output may change based on the current hour value)
2 Get hour of a specific date
In this example,
- We create a DateTime object
date
representing a specific date and time (2024-05-03 15:30 in this example). - We access the
hour
property ofdate
to get the hour of the day for that date. - We print the hour of the day to standard output.
Dart Program
void main() {
DateTime date = DateTime(2024, 5, 3, 15, 30);
int hourOfDay = date.hour;
print('Hour of the day: $hourOfDay');
}
Output
Hour of the day: 15
3 Get hour at midnight
In this example,
- We create a DateTime object
midnight
representing midnight on a specific date (2024-05-03 in this example). - We access the
hour
property ofmidnight
to get the hour at midnight for that date. - We print the midnight hour to standard output.
Dart Program
void main() {
DateTime midnight = DateTime(2024, 5, 3, 0, 0);
int midnightHour = midnight.hour;
print('Midnight hour: $midnightHour');
}
Output
Midnight hour: 0
Summary
In this Dart tutorial, we learned about hour property of DateTime: the syntax and few working examples with output and detailed explanation for each example.