Understanding and converting Mailgun event API timestamps

Hey everyone, I’m working with the Mailgun events API and I’m scratching my head over the timestamp format. The API returns timestamps like 1542251497.6072 or sometimes longer ones like 1542358648.178141. I’ve looked through their docs, but all I found was a mention of “RFC822” spec. It’s not helping much.

I’m trying to figure out how to turn these weird timestamps into regular JavaScript Date objects. Ideally, I’d like them in GMT. Has anyone dealt with this before? How did you handle it?

Here’s a quick example of what I’m dealing with:

const weirdTimestamp = 1542251497.6072;
// How do I turn this into a proper Date object?

function convertTimestamp(stamp) {
  // What goes here?
  return new Date(/* ... */);
}

const normalDate = convertTimestamp(weirdTimestamp);
console.log(normalDate);

Any tips or tricks would be super helpful. Thanks in advance!

I’ve encountered similar timestamp issues with Mailgun before. One thing to keep in mind is that these timestamps are Unix time with microsecond precision. While multiplying by 1000 works for most cases, you might lose some precision for timestamps with more decimal places.

For more accurate conversion, especially if you’re dealing with high-precision timing, you could use something like:

function convertTimestamp(stamp) {
  const [seconds, microseconds] = String(stamp).split('.');
  const ms = microseconds ? Number(microseconds.padEnd(3, '0').slice(0, 3)) : 0;
  return new Date(Number(seconds) * 1000 + ms);
}

This approach preserves microsecond precision by handling the decimal part separately. It’s a bit overkill for most use cases, but it can be crucial if you’re working with time-sensitive operations or data analysis where every microsecond counts.

Just remember to test thoroughly with various timestamp formats Mailgun might send your way. Their API can be a bit inconsistent sometimes.

hey neo, i’ve messed with those mailgun timestamps too. they’re actually unix timestamps in seconds. just multiply by 1000 to get milliseconds for javascript dates. here’s a quick function:

function convertTimestamp(stamp) {
return new Date(stamp * 1000);
}

ez pz! let me know if u need anything else

I’ve dealt with Mailgun’s timestamps before, and I can shed some light on this. Those numbers are actually Unix timestamps in seconds, with fractional seconds after the decimal point. To convert them to JavaScript Date objects, you need to multiply by 1000 (since JavaScript uses milliseconds).

Here’s a simple function that should do the trick:

function convertTimestamp(stamp) {
  return new Date(stamp * 1000);
}

This will give you a Date object in your local time zone. If you specifically need GMT, you can use the toUTCString() method:

const gmtDate = convertTimestamp(weirdTimestamp).toUTCString();

Hope this helps solve your timestamp puzzle!