How to add epoch time in terms of seconds in dart

Viewed 1726

How to add epoch time in terms of seconds in dart for eg:

static int TIMESTAMP = new DateTime.now().microsecondsSinceEpoch;

But I don't want it in microseconds I want the timestamp in epoch seconds format.

2 Answers

The Dart DateTime object only exposes SinceEpoch functionality for milliseconds and microseconds, but gettings seconds instead is as simple as:

int secondsSinceEpoch = date.millisecondsSinceEpoch ~/ Duration.millisecondsPerSecond;

where Duration.millisecondsPerSecond is just a long way of writing 1000.

Going the other direction is equally simple:

var date = DateTime.fromMillisecondsSinceEpoch(secondsSinceEpoch * 1000);

Let assume the epoch = 1653760800 that's in seconds, then to covert to a human date in dart:

import 'package:intl/intl.dart';

main() {
var dt =DateFormat('dd/MM/yyyy').format(DateTime.fromMillisecondsSinceEpoch(1653760800 *1000)).toString();
print(dt);
}

Output:

28/05/2022
Related