Dart DateTime weekday
Syntax & Examples
Syntax of DateTime.weekday
The syntax of DateTime.weekday property is:
int weekday
This weekday property of DateTime the day of the week monday..sunday.
Return Type
DateTime.weekday returns value of type int
.
✐ Examples
1 Get the day of the week for the current date
In this example,
- We create a variable
date
representing the current date and time usingDateTime.now()
. - We access the
weekday
property ofdate
to get the day of the week as an integer (1-7, where 1 represents Monday and 7 represents Sunday). - We print the day of the week to standard output. Output varies depending on the parsed date and time.
Dart Program
void main() {
var date = DateTime.now();
print(date.weekday); // Output: 1-7 (Monday-Sunday)
}
Output
5
2 Store and print the day of the week
In this example,
- We create a variable
date
representing a specific date and time usingDateTime.utc()
. - We assign the day of the week from
date.weekday
to a variabledayOfWeek
. - We then print the day of the week using string interpolation.
Dart Program
void main() {
var date = DateTime.utc(2021, 5, 3, 10, 15, 30);
var dayOfWeek = date.weekday;
print('Day of the week: $dayOfWeek'); // Output: Day of the week: 1-7 (Monday-Sunday)
}
Output
Day of the week: 1
3 Print the current day of the week directly
In this example,
- We create a variable
date
representing a specific date and time usingDateTime.parse()
. - We assign the day of the week from
date.weekday
to a variabledayOfWeek
. - We print the day of the week directly using string interpolation.
Dart Program
void main() {
var date = DateTime.parse('2029-05-03T10:15:30');
var dayOfWeek = date.weekday;
print('Day of the week: $dayOfWeek'); // Output: Day of the week: 1-7 (Monday-Sunday)
}
Output
Day of the week: 4
Summary
In this Dart tutorial, we learned about weekday property of DateTime: the syntax and few working examples with output and detailed explanation for each example.