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:
How to Get Current Timestamp:
int timestamp = DateTime.now().millisecondsSinceEpoch;
print(timestamp); //output: 1638592424384DateTime.now().millisecondsSinceEpoch returns the current Timestamp in Dart, you can use this cond in Flutter and use the returned Timestamp for your purpose.
How to Convert Timestamp to DateTime:
int ts = 1638592424384;
DateTime tsdate = DateTime.fromMillisecondsSinceEpoch(timestamp);
String datetime = tsdate.year.toString() + "/" + tsdate.month.toString() + "/" + tsdate.day.toString();
print(datetime); //output: 2021/12/4Here\u00a0DateTime.fromMillisecondsSinceEpoch(timestamp) converts Timestamp integer to DateTime, you can further use converted DateTime in various ways.
How to Convert Date String to Timestamp:
String sdatetime = "2021-12-04";
DateTime sdate = DateTime.parse(sdatetime);
int stimestamp = sdate.microsecondsSinceEpoch;
print(stimestamp); //output: 1638555300000000Here, we have converted the date and time string to the DateTime variable, and get the timestamp from the parsed DateTime.
How to Convert Timestamp to Formatted Date and Time:
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.0Now 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-2021In this way, you can get the current Timestamp in Dart and Flutter, and convert it to DateTime. To format raw epoch timestamps into readable strings, see formatting date and time in Flutter and getting the current formatted date and time.
Updated Flutter Example
High-Precision Unix Timestamps & Parsing
Key Implementation Details & Modern Differences:
- Native Epoch Precision: Employs
millisecondsSinceEpochandmicrosecondsSinceEpochwithout external time libraries. - Deterministic ISO Formatting: Uses standard Dart
DateTime.fromMillisecondsSinceEpoch()with explicit UTC flag support. - Material 3 Time Inspection: Displays high-precision telemetry and timestamp conversions with color-coded chip cards.
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: ModernTimestampDemo()));
}
/// Utility for Unix epoch timestamps in milliseconds and microseconds.
class ModernTimestampService {
/// Returns current Unix epoch timestamp in milliseconds.
static int currentMilliseconds() => DateTime.now().millisecondsSinceEpoch;
/// Returns current Unix epoch timestamp in microseconds for high-precision telemetry.
static int currentMicroseconds() => DateTime.now().microsecondsSinceEpoch;
/// Converts millisecond timestamp to seconds.
static int toSeconds(int milliseconds) => (milliseconds / 1000).floor();
/// Parses millisecond timestamp into a DateTime object.
static DateTime parseMilliseconds(int milliseconds, {bool isUtc = false}) {
return DateTime.fromMillisecondsSinceEpoch(milliseconds, isUtc: isUtc);
}
/// Formats timestamp as human-readable string.
static String formatTimestamp(int milliseconds) {
final dt = parseMilliseconds(milliseconds);
final y = dt.year.toString().padLeft(4, '0');
final m = dt.month.toString().padLeft(2, '0');
final d = dt.day.toString().padLeft(2, '0');
final h = dt.hour.toString().padLeft(2, '0');
final min = dt.minute.toString().padLeft(2, '0');
final s = dt.second.toString().padLeft(2, '0');
return '$y-$m-$d $h:$min:$s';
}
}
class ModernTimestampDemo extends StatefulWidget {
const ModernTimestampDemo({super.key});
@override
State<ModernTimestampDemo> createState() => _ModernTimestampDemoState();
}
class _ModernTimestampDemoState extends State<ModernTimestampDemo> {
late int _currentMs;
late int _currentUs;
@override
void initState() {
super.initState();
_refreshTimestamps();
}
void _refreshTimestamps() {
setState(() {
_currentMs = ModernTimestampService.currentMilliseconds();
_currentUs = ModernTimestampService.currentMicroseconds();
});
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Scaffold(
appBar: AppBar(title: const Text('Unix Timestamp Architecture')),
body: SingleChildScrollView(
padding: const EdgeInsets.all(20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Card(
elevation: 0,
color: theme.colorScheme.surfaceContainerHighest,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
children: [
Text(
'EPOCH MILLISECONDS',
style: theme.textTheme.labelMedium?.copyWith(
color: theme.colorScheme.primary,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 8),
Text(
'$_currentMs',
key: const Key('ms-timestamp-text'),
style: theme.textTheme.headlineMedium?.copyWith(
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 8),
Text(
'Readable: ${ModernTimestampService.formatTimestamp(_currentMs)}',
style: theme.textTheme.bodyMedium,
),
],
),
),
),
const SizedBox(height: 16),
Card(
elevation: 0,
color: theme.colorScheme.surfaceContainerLow,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Precision Comparison:',
style: theme.textTheme.titleSmall,
),
const SizedBox(height: 8),
Text(
'Seconds: ${ModernTimestampService.toSeconds(_currentMs)} s',
),
Text('Milliseconds: $_currentMs ms'),
Text('Microseconds: $_currentUs µs'),
],
),
),
),
const SizedBox(height: 20),
FilledButton.icon(
onPressed: _refreshTimestamps,
icon: const Icon(Icons.refresh),
label: const Text('Capture New Timestamp'),
),
],
),
),
);
}
}
Document History & Archival Record
Original reference snapshot archived March 22, 2023. Updated working solution verified on modern Flutter & Dart SDKs.