Type DateTime can't be converted to number

Title. Type DateTime can’t be converted to a number using tonumber

print(tonumber(DateTime.now())) -- nil

Strange, because DateTime.now() returns a unix timestamp, which seemingly has no reason to not be able to convert to a number, given that a unix timestap is just a number.

It would somewhat make sense if it just wasn’t able to convert to anything because it also has properties, such as UnixTimestampMillis, however, they can convert to a string using tostring just fine, and the doc for DateTime even mentions that.

This does allow for a workaround to this, which is just:

print(tonumber(tostring(DateTime.now()))) -- Returns the current unix timestamp as a number

Not sure if there’s some kind of internal limitation that only allows for string conversions to work with this, but ideally, whenever possible, it should also convert to a number without the need to convert to a string first.

That’s because DateTime.now() returns a DateTime object, not a number or a string (which is required when using tonumber).

You can test this out by running something like

print(DateTime.now() + 3)

Which would yield an error:

image

Using tonumber on a tostring’d version of DateTime.now() works because it probably has an underlying __tostring metamethod that converts itself to a numerical string whenever tostring is called on it.

2 Likes

Thank you for reaching out.

As has been answered by @VegetationBush tonumber only works on numbers and strings and doesn’t attempt to reinterpret other types, retuning ‘nil’.

You can use DateTime.now().UnixTimestamp to get the number.

1 Like