JavaScript : Date Formats

JavaScript provides several methods to format dates into human-readable strings. Here are some common date formats and how to achieve them using JavaScript:

1. ISO 8601 Date Format:


The ISO 8601 format represents a date and time in the following format: YYYY-MM-DDTHH:mm:ss.sssZ.


let date = new Date();
let isoString = date.toISOString();
console.log(isoString); // Example output: "2022-04-14T10:30:00.000Z"

 

2. Long Date Format (e.g., April 14, 2022):


You can use the toLocaleDateString() method to format a date into a long date string based on the user's locale.


let date = new Date();
let longDateString = date.toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });
console.log(longDateString); // Example output: "Thursday, April 14, 2022"

 

3. Short Date Format (e.g., 04/14/2022):


You can use the toLocaleDateString() method with appropriate options to format a date into a short date string.


let date = new Date();
let shortDateString = date.toLocaleDateString('en-US', { month: '2-digit', day: '2-digit', year: 'numeric' });
console.log(shortDateString); // Example output: "04/14/2022"

 

4. Long Time Format (e.g., 10:30:00 AM):


You can use the toLocaleTimeString() method to format a time into a long time string based on the user's locale.


let date = new Date();
let longTimeString = date.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: true });
console.log(longTimeString); // Example output: "10:30:00 AM"

 

5. Short Time Format (e.g., 10:30 AM):


Similar to the long time format, but with the hour12 option set to true.


let date = new Date();
let shortTimeString = date.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: true });
console.log(shortTimeString); // Example output: "10:30 AM"

 

 6. Custom Date Formats:


You can also create custom date formats using string manipulation or third-party libraries like moment.js.


let date = new Date();
let customFormat = `${date.getMonth() + 1}/${date.getDate()}/${date.getFullYear()}`;
console.log(customFormat); // Example output: "4/14/2022"

 

These are some common date formats used in JavaScript applications. Depending on your specific requirements and the preferences of your users, you can choose the appropriate format or combination of formats to display dates and times in a user-friendly manner.