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-
Top comments (4)
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.
hi Andrei Dascalu! never heard about luxon. But i will definitely try it out.
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)
Hi Luke! Any advantage over momentjs?