How to get the current date or/and time in seconds
Here's a quick bite at the task of retrieving the current time in seconds with JavaScript's Date.now()
method. It gives milliseconds since Epoch, divide by 1000 to get seconds:
This line of code gifts you the Epoch time packed in a seconds
integer.
Battle against time zones and daylight saving
Every Timelord knows, dealing with timestamps is a perilous journey between time zones and through daylight saving time. Remember, the tardis that is Date.now()
journeys only in UTC. But not all of us live in UTC, eh? You're gonna need the local time:
Notice how we convert the time zone offset from minutes to milliseconds to make our calculations easier. Interesting trick, right?
Playing nice with multiple browsers
All is not friendly in the land of browsers. You see, Date.now()
method doesn't get along well with Internet Explorer 8 and its earlier siblings. This sibling rivalry can be fixed with new Date().getTime()
:
Now, this method is the way to third-party peace, giving consistency across various versions of browsers.
Pinning down precise and rounded timestamps
Keeping things precise is akin to being a good marksman, especially when it's about token expiration or event logging. Always aim for the closest second:
Sometimes, the aim might need to be a little lower, to get the timestamp floor value:
Some say it's about the shot, I say it's about the target. No matter what you find, happy hunting!
Y2038: Coming to a computer near you
The Year 2038 problem is the Y2K bug's angrier cousin. This is when 32-bit systems will throw a tantrum and just plainly refuse to represent dates correctly after January 2038. To avoid being shunned at family gatherings, consider switching to 64-bit systems or aligning with date-time libraries that can handle this.
The daily grind: Practical scenarios and manipulations
Adding minutes to a timestamp or chasing the rabbit (aka checking for timeouts) are common chores:
Remember, no "bitwiseing" around. Avoid using bitwise operators on timestamps, you could end up attracting unwanted bugs.
"Float" you might have an issue
When your timestamp starts floating down the river (very punny, I know) remember that floating-point precision can be a plague. Safer to bank on integer values and switch raft to floating points only when you have to.
Was this article helpful?