DEV Community

loading...
Cover image for Javascript Format Date without Moment.js (Eg: 17 July, 2021 )

Javascript Format Date without Moment.js (Eg: 17 July, 2021 )

Jyotishman Saikia
Technical Lead at Dotpe | Follow on twitter for more educational frontend tips @frontend_jsx
・1 min read

Almost everyone like me might be using the plugin moment.js to format a date-time-stamp to a readable date or time - Eg: 14 July 2021 or 11:58 pm

Fortunately, there is a native javascript API to format date and time.

Demo and Example to format date:

With the help of toLocaleDateString we can format a date-time-stamp to a readable language sensitive representation.

const date = new Date();

Sat Jul 17 2021 19:04:31 GMT+0530 (India Standard Time)

date.toLocaleDateString("en-IN", {
"year": "numeric",
"month": "long",
"day": "numeric"
})

"17 July 2021"

(Formatted Date)

Demo and Example to format time:

With the help of toLocaleTimeString we can format a date-time-stamp to a readable language sensitive representation.

const date = new Date();

Sat Jul 17 2021 19:04:31 GMT+0530 (India Standard Time)

date.toLocaleTimeString("en-IN", {"hour": "numeric"})

"7 pm"

(Formatted Time)

If you liked my content you can follow me on twitter for more such content-

https://twitter.com/frontend_jsx

Discussion (6)

Collapse
andreidascalu profile image
Andrei Dascalu

Well, formatting the date doesn't require moment. Moment is best for operating on dates and timezones.
On the other hand moment has been deprecate for quite a while now. I myself moved to luxon.

Collapse
jyotishman profile image
Jyotishman Saikia Author

hi Andrei Dascalu! never heard about luxon. But i will definitely try it out.

Collapse
lukeshiru profile image
LUKESHIRU

You need to try date-fns, is by far the best alternative.

Collapse
jyotishman profile image
Jyotishman Saikia Author

Hi Luke! Any advantage over momentjs?

Thread Thread
lukeshiru profile image
LUKESHIRU • Edited

Moment JS is pretty much deprecated, and is extremely heavy. The alternatives make better use of native functions and methods and are way lighter than Moment.

Thread Thread
andreidascalu profile image
Andrei Dascalu

Any alternative library has the huge advantage of being maintained and as such will make use of latest JS features.
On date-fns so far I like its composable functions.
On Luxon, I like that despite it being a fairly straightforward drop-in replacements , it offers an immutable object by default (much like PHP's Chronos library)