Ayush Shekhar
Ayush Shekhar

Reputation: 1563

What is the Dart/Flutter equivalent of PHP's gmmktime()?

I need to calculate the value in Dart/Flutter, as calculated by the gmmktime() function in PHP.

This is what I was trying till now:

var ms = (DateTime.now().toUtc().millisecondsSinceEpoch)/100;
int ms = DateTime.now().toUtc().millisecondsSinceEpoch;

But both of these approaches give a value, which is not expected by this API in its header, here: https://api.kitewalk.com/#authentication

Upvotes: 1

Views: 341

Answers (1)

jamesdlin
jamesdlin

Reputation: 90135

PHP's gmmktime is documented to return "Unix time", which is the number of seconds since the the "Unix epoch".

Your first approach was almost right, but you didn't convert from milliseconds to seconds correctly. There are 1000 milliseconds in a second, so you need to divide by 1000, not 100. Additionally, whatever you're passing the time to probably expects an integral number of seconds and not a floating point value, so you'll need to use integer division or round the quotient afterward.

Also note that the "Unix epoch" is not time-zone dependent; DateTime.millisecondsSinceEpoch already measures against a fixed point in time, so an explicit conversion to UTC isn't necessary (but it doesn't hurt).

A correct version would be:

var unixTime = DateTime.now().millisecondsSinceEpoch ~/ 1000;

Upvotes: 3

Related Questions