In the realm of web development, managing and presenting dates is a common task. Whether you’re crafting a scheduling app, a calendar, or just displaying timestamps on a blog post, understanding how to format dates in JavaScript is essential. Dive deep into the world of JavaScript date formatting with our comprehensive guide, complete with real-world examples.
A new Date
instance, without arguments, creates an object representing the current date and time:
Key JavaScript Date methods
getFullYear() – Returns the year of a date.
getMonth() – Returns the month of a date (0-11, where 0 is January).
getDate() – Returns the day of the month (1-31).
getDay() – Returns the day of the week (0-6, where 0 is Sunday).
getHours(), getMinutes(), getSeconds(), and getMilliseconds() – Return the respective time components.
Formatting dates in JavaScript
Now, onto the crux of our guide — formatting dates. There isn’t a built-in method like .format() as in some languages. However, combining the above methods allows us to customize our date presentation:
Example: A common format is YYYY-MM-DD
:
Note that we added + 1
to the month, as JavaScript months start from 0.
Output
Using libraries for enhanced formatting
For more complex formatting, libraries like Moment.js come to the rescue.
Example with Moment.js:
Get more articles on Java Script
Read more on Shell and Linux related articles
Refer more on python here : Python