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:
const currentDate = new Date();
console.log(currentDate);
Key JavaScript Date methods
getFullYear() – Returns the year of a date.
const date = new Date("2023-10-27");
const year = date.getFullYear();
console.log(year); // Outputs: 2023
getMonth() – Returns the month of a date (0-11, where 0 is January).
const date = new Date("2023-10-27");
const month = date.getMonth();
console.log(month); // Outputs: 9 (because October is the 10th month, but counting starts from 0)
getDate() – Returns the day of the month (1-31).
const date = new Date("2023-10-27");
const dayOfMonth = date.getDate();
console.log(dayOfMonth); // Outputs: 27
getDay() – Returns the day of the week (0-6, where 0 is Sunday).
const date = new Date("2023-10-27"); // This is a Friday
const dayOfWeek = date.getDay();
console.log(dayOfWeek); // Outputs: 5 (because Sunday is 0 and Friday is 5)
getHours(), getMinutes(), getSeconds(), and getMilliseconds() – Return the respective time components.
const date = new Date("2023-10-27T15:45:30.123");
// Get Hours
const hours = date.getHours();
console.log(hours); // Outputs: 15
// Get Minutes
const minutes = date.getMinutes();
console.log(minutes); // Outputs: 45
// Get Seconds
const seconds = date.getSeconds();
console.log(seconds); // Outputs: 30
// Get Milliseconds
const milliseconds = date.getMilliseconds();
console.log(milliseconds); // Outputs: 123
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
:
const today = new Date();
const formattedDate = `${today.getFullYear()}-${today.getMonth() + 1}-${today.getDate()}`;
console.log(formattedDate);
Note that we added + 1
to the month, as JavaScript months start from 0.
Output
2023-10-28
Using libraries for enhanced formatting
For more complex formatting, libraries like Moment.js come to the rescue.
Example with Moment.js:
const moment = require('moment');
console.log(moment().format('MMMM Do YYYY, h:mm:ss a'));
Get more articles on Java Script
Read more on Shell and Linux related articles
Refer more on python here : Python