Dates in Javascript have always been a PITA. It is one of the reasons that libraries like MomentJS reigned supreme for so long. Things are complicated, especially if you’re dealing with different timezones. Fortunately, working with simple DATETIME values has never really been a problem.
What prompted this post was that I am working with WordPress a lot at the moment, and all dates in WordPress are MySQL DATETIME formatted dates. Say you have a DATETIME value that looks like this: 2021-10-05 00:00:00 — you can use the Javascript Date object on this because it’s a valid date value.
In your developer tools in the browser, you can pass this value into Date
and it will spit out something that looks like the below:
For brevity, here is the code itself:
new Date('2021-10-05 00:00:00');
Get the UNIX timestamp
So, you have your date object. You can now easily convert the value to a UNIX timestamp using getTime()
. This allows you to do things like sort elements by integers instead of date objects. You can do safe comparative checks and use the .sort
method.
Here is the code:
Math.floor(new Date('2021-10-05 00:00:00').getTime() / 1000);
We have to divide this value by 1000 because the Javascript getTime()
will return milliseconds since the UNIX epoch. Unix time is in seconds, so dividing the milliseconds gives us the seconds representation.
The reason we use Math.floor
here is quite important too. Some examples online will use Math.round
which is not accurate. We want the actual elapsed seconds and using floor will not give us that. Because dividing by 1000 can sometimes result in fractional numbers, we use this to get a nice clean value.
Chances are, if you’re reading this, you’re working with dates that are coming from a database like MySQL. Luckily, Javascript makes working with these dates relatively painless. Just don’t mention timezones. That conversation is for another post entirely.