Convert epoch time into timestamp flutter

Viewed 2374

I have a date-time in epoch format: 1633247247

I want to convert it into timestamps like this: Sunday, 3 October 2021 or just October 3 2021

I am writing this code

final DateTime timeStamp = DateTime.fromMillisecondsSinceEpoch(1633247247);

But it is returning 1970-01-19 18:25:11.247

Edit I ran this code

final DateTime timeStamp = DateTime.fromMillisecondsSinceEpoch(1633247247 * 1000);

Got the output in datetime. I am now trying to convert into string

String formattedDate = DateFormat('yyyy-MM-dd – kk:mm').format(date);

It gives this error The instance member 'date' can't be accessed in an initializer.

4 Answers

It represent to milliseconds, you need to multiple it with 1000 like below :

final DateTime timeStamp = DateTime.fromMillisecondsSinceEpoch(1633247247 * 1000);

It seems like that the time you've is 'seconds since epoch' so just multiplying by 1000 should give you the correct time.

final DateTime timeStamp = DateTime.fromMillisecondsSinceEpoch(1633247247 * 1000);

Download and Import

intl Pacakge

import 'package:intl/intl.dart';

Initialize a variable

String datetime;

Get Current date and conversion

Future<void> Datetimes() async{
  setState(() {
    DateTime now = DateTime.now();
    String formattedDate = DateFormat('EEEE d MMM hh:mm:ss').format(now);
    datetime=formattedDate;
  });
}

Output

Saturday 3 oct 2:07:29

Refer this for DateandTime class for more formatting parameters DateFormat-class

Related