How to Get Timestamp in Dart/Flutter

In this example, we are going to show you how to get the current Timestamp in Dart or Flutter, and convert it to Formatted Date and Time or Convert DateTime to Timestamp. See the example below:

int timestamp = DateTime.now().millisecondsSinceEpoch;
print(timestamp); //output: 1638592424384

DateTime.now().millisecondsSinceEpoch returns the current Timestamp in Dart, you can use this cond in Flutter and use the returned Timestamp for your purpose.

int ts = 1638592424384;
DateTime tsdate = DateTime.fromMillisecondsSinceEpoch(timestamp);
String datetime = tsdate.year.toString() + "/" + tsdate.month.toString() + "/" + tsdate.day.toString();
print(datetime); //output: 2021/12/4

Here DateTime.fromMillisecondsSinceEpoch(timestamp) converts Timestamp integer to DateTime, you can further use converted DateTime in various ways.

String sdatetime = "2021-12-04";
DateTime sdate = DateTime.parse(sdatetime);
int stimestamp = sdate.microsecondsSinceEpoch;
print(stimestamp); //output: 1638555300000000

Here, we have converted the date and time string to the DateTime variable, and get the timestamp from the parsed DateTime.

To format DateTime in Flutter, you need to add intl Flutter package in your project by adding the following lines in pubspect.yaml file.

dependencies:
  flutter:
    sdk: flutter
  intl: ^0.17.0

Now Format Timestamp to Date and Time:

import 'package:intl/intl.dart';
int ts = 1638592424384;
DateTime tsdate = DateTime.fromMillisecondsSinceEpoch(timestamp);
String fdatetime = DateFormat('dd-MMM-yyy').format(tsdate); //DateFormat() is from intl package
print(fdatetime); //output: 04-Dec-2021

In this way, you can get the current Timestamp in Dart and Flutter, and convert it to DateTime.

No any Comments on this Article


Please Wait...