Dart/Flutter - Get Current Date Time & Timestamp

This tutorial explains how to get the current date time value in Dart.

Dart has a DateTime class that can be used to store time instants. That class also provides the functionality to get the current date time. Below are some examples that work in Dart or any framework using Dart such as Flutter.

Get Current Date Time

Getting the current time is very simple. You can use the named constructor below.

  final currentTime = DateTime.now();

By default, the created instance uses the system's local time. You can check it from the timeZoneName or timeZoneOffset property. If you want to convert it to UTC, just call the toUtc() method.

  final currentTimeUtc = currentTime.toUtc();

Get Current Date Without Time

What if you want to get the current date without time. Dart doesn't have any type that represents the date components only, so you have to use DateTime. The now() constructor always returns the time components. If you want to have the date components only (which means the time is set to 00:00:00.000), just create another DateTime instance using the constructor below. As you can see, it has some positional arguments. But the only required one is the year. That means if you want to have an instance that contains the date components only, just pass the first three arguments (year, month, and day).

  DateTime(
    int year,
    [
      int month = 1,
      int day = 1,
      int hour = 0,
      int minute = 0,
      int second = 0,
      int millisecond = 0,
      int microsecond = 0
    ]
  )

Below is the example. If you want to get the year only or year +month only, you can do the similar thing by only passing necessary arguments.

  final currentDate = DateTime(
    currentTime.year,
    currentTime.month,
    currentTime.day,
  );

If you print the variable above, the time components will be printed as 00:00:00.000. However, it's possible to convert the date to a string using any format you want.

Get Current Unix Epoch Timestamp

In computer systems, it's very common to get the time representation as the elapsed time since the epoch time. The epoch time itself is 1 January 1970 at 00:00:00 UTC. From a currentTime variable above, you can get the milliseconds and microseconds since epoch from the millisecondsSinceEpoch and microsecondsSinceEpoch properties respectively.

  print(currentTime.millisecondsSinceEpoch);
  print(currentTime.microsecondsSinceEpoch);

Summary

Getting the current date time in Dart can be done using DateTime.now() constructor. Then, you can convert it to a UTC time, construct another instance with certain components only, or get the milliseconds/microseconds since Unix epoch.

You can also read about: