UnixTime@DateObject@"2017-05-05T01:02:30.5Z"
gives the seconds, rounded to an integer, so I can't simply multiply it by 1000 to get the milliseconds. How can I get milliseconds without doing date arithmetic?
3 Answers
There is a fixed offset between AbsoluteTime
and UnixTime
, so you can use AbsoluteTime
instead of UnixTime
if you want subsecond resolution. For example:
ut = (#-2208963600&)@*AbsoluteTime;
Then:
UnixTime[Today]
ut[Today]
1509692400
1509692400
and:
UnixTime[Now]
ut[Now]
1509740426
1.509740426703258*10^9
For your example:
UnixTime @ DateObject @ "2017-05-05T01:02:30.5Z"
ut @ DateObject @ "2017-05-05T01:02:30.5Z" //InputForm
1493971350
1.4939713505*^9
-
1$\begingroup$
DateObject @ "2017-05-05T01:02:30.5Z"
is not what you think it is. mathematica.stackexchange.com/q/144764/5478 $\endgroup$– KubaCommented Nov 3, 2017 at 20:48 -
$\begingroup$ @Kuba I just copied what the OP had, you should probably be commenting on the OP use of that idiom instead. My point was that my version
ut
provides the fractional seconds they wanted. $\endgroup$ Commented Nov 3, 2017 at 21:20 -
$\begingroup$ That was fyi, nothing more. And yes I could comment on OP but it already has more comments so here it can get more attention. $\endgroup$– KubaCommented Nov 3, 2017 at 21:29
-
$\begingroup$ Yes, I noticed that it doesn't parse the Z at the end. Thanks for pointing it out. $\endgroup$– AshleyCommented Nov 6, 2017 at 15:30
The best I could come up with is f[d_String] :=
Module[{do = DateObject[d, TimeZone -> "GMT"]},
1000 * UnixTime@DateObject@do +
DateValue[DateObject@do, "Millisecond"]]
.
If you want the current time in milliseconds since Epoch,
ToExpression[ToString[UnixTime[]] <> DateString["Millisecond"]]
I don't know how accurate it is given there are two functions called at different times so I can only assume there is a slight variation between the "true" time with milliseconds and this solution.
UnixTime[]
1509763110
ToExpression[ToString[UnixTime[]] <> DateString["Millisecond"]]
1509763110487
Block[{$TimeZone = 0}, UnitConvert[DateDifference[DateObject["1970-01-01T00:00:00Z"], DateObject["2017-05-05T01:02:30.5Z"], "Seconds"], "Milliseconds"]]
. $\endgroup$