Dart DateTime()
Syntax & Examples
Syntax of DateTime
The syntax of DateTime.DateTime constructor is:
DateTime(int year, [int month = 1, int day = 1, int hour = 0, int minute = 0, int second = 0, int millisecond = 0, int microsecond = 0])This DateTime constructor of DateTime constructs a DateTime instance specified in the local time zone.
Parameters
| Parameter | Optional/Required | Description |
|---|---|---|
year | required | the year component of the DateTime |
month | optional [default value is 1] | the month component of the DateTime |
day | optional [default value is 1] | the day component of the DateTime |
hour | optional [default value is 0] | the hour component of the DateTime |
minute | optional [default value is 0] | the minute component of the DateTime |
second | optional [default value is 0] | the second component of the DateTime |
millisecond | optional [default value is 0] | the millisecond component of the DateTime |
microsecond | optional [default value is 0] | the microsecond component of the DateTime |
✐ Examples
1 Create a DateTime with only the year
In this example,
- We create a DateTime named
dateTime1with the year 2024. - We print
dateTime1to standard output, which displays the date and time representation of the DateTime in the local time zone.
Dart Program
void main() {
DateTime dateTime1 = DateTime(2024);
print(dateTime1);
}Output
2024-01-01 00:00:00.000
2 Create a DateTime with specific date and time components
In this example,
- We create a DateTime named
dateTime2with the year 2023, month 12, and day 31. - We print
dateTime2to standard output, which displays the date and time representation of the DateTime in the local time zone.
Dart Program
void main() {
DateTime dateTime2 = DateTime(2023, 12, 31);
print(dateTime2);
}Output
2023-12-31 00:00:00.000
3 Create a DateTime with full date and time components
In this example,
- We create a DateTime named
dateTime3with the year 2022, month 5, day 3, hour 12, and minute 30. - We print
dateTime3to standard output, which displays the date and time representation of the DateTime in the local time zone.
Dart Program
void main() {
DateTime dateTime3 = DateTime(2022, 5, 3, 12, 30);
print(dateTime3);
}Output
2022-05-03 12:30:00.000
Summary
In this Dart tutorial, we learned about DateTime constructor of DateTime: the syntax and few working examples with output and detailed explanation for each example.