0

I am returning some dates directly (unmodified) from the a database query to the front-end:

1540906457020

1540920856937

1540920856970

What is this dateformat called and how do I convert it to a human readable date, such as "03/21/2019" (or some variant with timestamp appended)?

8t12c7081
  • 683
  • 3
  • 9
  • 30

2 Answers2

1

This is a Unix timestamp (since Jan 01 1970), in milliseconds

You can convert it using e.g. this link here: https://www.epochconverter.com/

There are plenty of topics on how to convert timestamps to strings.

Start by using

new Date(1540920856937)
rst
  • 2,510
  • 4
  • 21
  • 47
  • Specifically, it's a _Unix_ timestamp (since Jan 01 1970), in milliseconds. – Roger Lipscombe Jul 03 '19 at 15:06
  • @RogerLipscombe—it's just a number that can be used as an [*ECMAScript time value*](http://ecma-international.org/ecma-262/10.0/#sec-time-values-and-time-range)). Mentioning UNIX is just a red herring, they both happen to use the same epoch (as do many programming languages and systems). – RobG Jul 03 '19 at 20:29
1

It's based on the Unix timestamp, but it's counting milliseconds rather than seconds. (ES2015 calls this the "Time Value".) The Date object in Javascript uses this value underneath the surface. If you use the integer value as a parameter in the Date constructor, you'll get a Date object which should be handled quite well by most browsers.

const happyDateObject = new Date(1540920856937);

If you want a bit more control over what's going on, or want some more utilities that help you customize what the date looks like and how to manipulate it, I'd recommend the moment.js library. It's widely used because it's so useful. Since it's really just a wrapper for the standard Javascript Date object, moment objects convert quite easily to Date objects (when you need to do so). You'd construct the value in a similar way:

const happyMoment = moment(1540920856937)
Philip Antin
  • 116
  • 1
  • 7