Unix Timestamp in Dart

Dart's DateTime works in milliseconds and has only UTC and local — named IANA zones need the timezone package.

Need to convert one value rather than write code? Use the interactive converter — it handles every unit and time zone without leaving your browser.

Current Unix timestamp

DateTime.now().millisecondsSinceEpoch;              // 1710050400000
DateTime.now().millisecondsSinceEpoch ~/ 1000;      // 1710050400
DateTime.now().microsecondsSinceEpoch;

Timestamp to date

final d = DateTime.fromMillisecondsSinceEpoch(1710050400 * 1000,
    isUtc: true);
print(d.toIso8601String());          // 2024-03-10T06:00:00.000Z
print(d.toLocal());

Date to timestamp

final d = DateTime.utc(2024, 3, 10, 6, 0, 0);
print(d.millisecondsSinceEpoch ~/ 1000);            // 1710050400

print(DateTime.parse('2024-03-10T06:00:00Z')
    .millisecondsSinceEpoch ~/ 1000);

Named time zones

import 'package:timezone/data/latest.dart' as tzdata;
import 'package:timezone/timezone.dart' as tz;

tzdata.initializeTimeZones();
final kolkata = tz.getLocation('Asia/Kolkata');
print(tz.TZDateTime.fromMillisecondsSinceEpoch(kolkata, 1710050400000));

Pitfalls specific to Dart

  • Use ~/ (integer division) rather than /, which returns a double and will render as 1710050400.0.
  • DateTime has no concept of named zones — everything is UTC or the device's local zone until you add the timezone package.

Rules that apply in every language

  1. Store UTC, display local. Keep the instant in UTC everywhere in your system and convert only at the point a human reads it.
  2. Name the unit in the identifier. expires_at_ms rather than expires_at costs nothing and prevents the single most common timestamp bug.
  3. Never trust a client clock. Stamp anything security-relevant on the server. See the note on clock skew.
  4. Use 64-bit time. Anything still storing seconds in a signed 32-bit field breaks in January 2038 — see the Year 2038 problem.

The same task in other languages

Frequently asked questions

How do I get the current Unix timestamp in Dart?

Use the snippet in the "Current Unix timestamp" section above. Dart / Flutter works in integer milliseconds natively, so converting to another unit is a multiplication or an integer division away.

How do I convert a Unix timestamp to a date in Dart?

The "Timestamp to date" snippet above shows the idiomatic approach, including how to render the result in a specific time zone rather than whatever zone the machine happens to be set to.

Does Dart handle time zones and daylight saving correctly?

Yes, provided you pass an explicit zone rather than relying on the system default. The gotchas listed on this page cover the specific ways Dart / Flutter makes that easy to get wrong.