Sandeep
Sandeep

Reputation: 65

Date Time format MM/dd/yyyy, HH:mm:ss a to milliseconds in Flutter

I have code like below

var date = DateTime.fromMillisecondsSinceEpoch(timeStamp);//timeStamp = 1630506255982
var d12 = DateFormat('MM/dd/yyyy, HH:mm:ss a').format(date); // 12/31/2021, 10:10:10 PM

Now I want to convert the d12 string back to timeStamp "1630506255982"

How can I achieve this in flutter code?

Upvotes: 1

Views: 3180

Answers (2)

FpB
FpB

Reputation: 325

You have to first call this import:

import 'package:intl/intl.dart';

Then base on your code, you can simply add the function that will convert it back to integer.

 var date = DateTime.fromMillisecondsSinceEpoch(1630506255982);//timeStamp = 1630506255982
 var d12 = DateFormat('MM/dd/yyyy, HH:mm:ss a').format(date); // 12/31/2021, 10:10:10 PM

  var _convertedDateBackToInt = (date.toUtc().millisecondsSinceEpoch ~/ 1000).toInt(); /// Converts back the base [DateTime] value to [int].
  print(_convertedDateBackToInt); // 1630506255982

Upvotes: 2

Omar Mahmoud
Omar Mahmoud

Reputation: 3067

Use it like this

   var dtime = DateFormat('MM/dd/yyyy, HH:mm:ss a').parse(d12);

   var inMilliseconds = dtime.millisecondsSinceEpoch

Upvotes: 2

Related Questions