Warm tip: This article is reproduced from stackoverflow.com, please click
date javascript

What date format is this? How do I convert it to a human readable date format in Javascript?

发布于 2020-03-27 10:26:21

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)?

Questioner
8t12c7081
Viewed
77
Philip Antin 2019-07-03 23:13

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)