Flochristos
Flochristos

Reputation: 33

How can i convert a DateTime variable "2022-09-29T07:26:52.000Z" to seconds in dart flutter?

I have a variable in dart string and would like to convert it all to seconds or minutes....

String x = "2022-09-29T07:26:52.000Z"

I want the opposite of this code below

final newYearsDay =
    DateTime.fromMillisecondsSinceEpoch(1640979000000, isUtc:true);
print(newYearsDay); // 2022-01-01 10:00:00.000Z

I want to be able to get this back to seconds from the current timedate formart

Upvotes: 1

Views: 2691

Answers (2)

Richard Heap
Richard Heap

Reputation: 51751

DateTime has a parse static that can parse many (but not all) date formats. The ISO8601 format is one that it can parse - including the trailing Z.

void main() {
  final dt1 = DateTime.parse('2022-09-29T07:26:52.000Z');

  print(dt1.millisecondsSinceEpoch ~/ 1000);
}

Upvotes: 1

eamirho3ein
eamirho3ein

Reputation: 17920

You can convert your string to a datetime by using intl like this:

String x = "2022-09-29T07:26:52.000Z";
var dateTime = DateFormat('yyyy-MM-ddThh:mm:ss').parse(x);

and for get the number of milliseconds since the Unix epoch :

print("numbers= ${dateTime.millisecondsSinceEpoch}")

Upvotes: 2

Related Questions