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

ParameterOptional/RequiredDescription
yearrequiredthe year component of the DateTime
monthoptional [default value is 1]the month component of the DateTime
dayoptional [default value is 1]the day component of the DateTime
houroptional [default value is 0]the hour component of the DateTime
minuteoptional [default value is 0]the minute component of the DateTime
secondoptional [default value is 0]the second component of the DateTime
millisecondoptional [default value is 0]the millisecond component of the DateTime
microsecondoptional [default value is 0]the microsecond component of the DateTime


✐ Examples

1 Create a DateTime with only the year

In this example,

  1. We create a DateTime named dateTime1 with the year 2024.
  2. We print dateTime1 to 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,

  1. We create a DateTime named dateTime2 with the year 2023, month 12, and day 31.
  2. We print dateTime2 to 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,

  1. We create a DateTime named dateTime3 with the year 2022, month 5, day 3, hour 12, and minute 30.
  2. We print dateTime3 to 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.