Published on

Generating Unix Timestamps for API Requests

Authors

TL;DR

const urlencoded = new URLSearchParams()
urlencoded.append('timestamp', Math.floor(new Date().getTime() / 1000).toString())

Context

I'm filing this one in the "better write this down so I don't make the same mistake again" folder.

I was recently working with an API that required a timestamp1 parameter as part of the URL's query string. My first instinct was to do something with Date.now(). Wrong! As the API later informed me:

400 Bad Request:
{
    'success':false,
    'data': {
        'name':'Bad Request',
        'message':'Timestamp has expired'
    }
}

Not using javascript/typescript? See here.

Footnotes

  1. aka Unix timestamp, POSIX time, Unix epoch