Dart DateTime.fromMillisecondsSinceEpoch()
Syntax & Examples


Syntax of DateTime.fromMillisecondsSinceEpoch

The syntax of DateTime.DateTime.fromMillisecondsSinceEpoch constructor is:

DateTime.fromMillisecondsSinceEpoch(int millisecondsSinceEpoch, {bool isUtc = false})

This DateTime.fromMillisecondsSinceEpoch constructor of DateTime constructs a new DateTime instance with the given millisecondsSinceEpoch.

Parameters

ParameterOptional/RequiredDescription
millisecondsSinceEpochrequiredthe milliseconds since epoch value to construct the DateTime
isUtcoptional [default value is false]whether the DateTime should be in UTC


✐ Examples

1 Create a DateTime from milliseconds since epoch

In this example,

  1. We create a DateTime named dateTime1 from milliseconds since epoch 1649070000000.
  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.fromMillisecondsSinceEpoch(1649070000000);
  print(dateTime1);
}

Output

2022-04-04 18:46:40.000

2 Create a UTC DateTime from milliseconds since epoch

In this example,

  1. We create a DateTime named dateTime2 from milliseconds since epoch 0, specifying that it should be in UTC.
  2. We print dateTime2 to standard output, which displays the date and time representation of the DateTime in UTC.

Dart Program

void main() {
  DateTime dateTime2 = DateTime.fromMillisecondsSinceEpoch(0, isUtc: true);
  print(dateTime2);
}

Output

1970-01-01 00:00:00.000Z

3 Create a DateTime from milliseconds since epoch

In this example,

  1. We create a DateTime named dateTime3 from milliseconds since epoch 1609459200000.
  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.fromMillisecondsSinceEpoch(1609459200000);
  print(dateTime3);
}

Output

2021-01-01 00:00:00.000

Summary

In this Dart tutorial, we learned about DateTime.fromMillisecondsSinceEpoch constructor of DateTime: the syntax and few working examples with output and detailed explanation for each example.