1

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

  • Do you mean convert to dateTime ? – Md. Yeasin Sheikh Oct 21 '22 at 18:29
  • I'm not sure, I just want to get the equivalent in hours or minutes or seconds... – Flochristos Oct 21 '22 at 18:33
  • what will be the current string output? – Md. Yeasin Sheikh Oct 21 '22 at 18:34
  • 2
    @Flochristos What does that mean? If you want the number of seconds since the Unix "epoch", see [How do I convert a date/time string to a DateTime object in Dart?](https://stackoverflow.com/q/49385303/) to get a `DateTime` object, and then you can use `dateTime.millisecondsSinceEpoch ~/ 1000`. If that's not what you want, then provide an *example* of what you do want. – jamesdlin Oct 21 '22 at 18:35
  • @YeasinSheikh something like "37684904983040504" seconds – Flochristos Oct 21 '22 at 18:37
  • @jamesdlin i want the exact opposite of what you just said.. ```final newYearsDay = DateTime.fromMillisecondsSinceEpoch(1640979000000, isUtc:true); print(newYearsDay); // 2022-01-01 10:00:00.000Z``` Opposite of this, to turn back the datetime to seconds – Flochristos Oct 21 '22 at 18:39
  • How you've reached to `37684904983040504` seconds – Md. Yeasin Sheikh Oct 21 '22 at 18:47

2 Answers2

1

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}")
eamirho3ein
  • 16,619
  • 2
  • 12
  • 23
1

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);
}
Richard Heap
  • 48,344
  • 9
  • 130
  • 112