Dart DateTime year
Syntax & Examples
Syntax of DateTime.year
The syntax of DateTime.year property is:
int year
This year property of DateTime the year.
Return Type
DateTime.year returns value of type int
.
✐ Examples
1 Get the year of the current DateTime
In this example,
- We create a DateTime object
dt
using theDateTime.now()
constructor, which represents the current date and time. - We then access the
year
property ofdt
to get the year. - We print the result to standard output. Output varies depending on the parsed date and time.
Dart Program
void main() {
var dt = DateTime.now();
print(dt.year);
}
Output
2024
2 Get the year of a specific DateTime in UTC
In this example,
- We create a DateTime object
dt
using theDateTime.utc()
constructor, specifying the year, month, day, hour, minute, and second. - We then access the
year
property ofdt
to get the year. - We print the result to standard output. Output varies depending on the parsed date and time.
Dart Program
void main() {
var dt = DateTime.utc(2021, 5, 3, 10, 15, 30);
print(dt.year);
}
Output
2021
3 Get the year of a parsed DateTime
In this example,
- We create a DateTime object
dt
by parsing a date-time string '2024-05-03T10:15:30' using theDateTime.parse()
method. - We then access the
year
property ofdt
to get the year. - We print the result to standard output. Output varies depending on the parsed date and time.
Dart Program
void main() {
var dt = DateTime.parse('2029-05-03T10:15:30');
print(dt.year);
}
Output
2029
Summary
In this Dart tutorial, we learned about year property of DateTime: the syntax and few working examples with output and detailed explanation for each example.