How do I format a Javascript Date object as a string? (Preferably in the format: 10-Aug-2010)

 

In JavaScript, you can format a Date object as a string using various methods, including the toLocaleDateString() method or custom formatting using libraries like moment.js or by writing your own formatting function. Here's an example using the toLocaleDateString() method:

javascript
// Create a Date object const date = new Date('2010-08-10'); // Format the Date object using toLocaleDateString() const formattedDate = date.toLocaleDateString('en-US', { day: '2-digit', month: 'short', year: 'numeric' }); console.log(formattedDate); // Output: Aug 10, 2010

However, the specific format you mentioned (10-Aug-2010) is not directly supported by toLocaleDateString(). To achieve that custom format, you might need to create your own formatting function or use a library like moment.js.

Here's an example using moment.js:

javascript
// Assuming you have moment.js library included const date = new Date('2010-08-10'); const formattedDate = moment(date).format('DD-MMM-YYYY'); console.log(formattedDate); // Output: 10-Aug-2010

If you prefer to avoid using external libraries, you can create your own formatting function:

javascript
const months = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]; function formatDate(date) { const day = date.getDate(); const month = months[date.getMonth()]; const year = date.getFullYear(); return `${day}-${month}-${year}`; } const date = new Date('2010-08-10'); const formattedDate = formatDate(date); console.log(formattedDate); // Output: 10-Aug-2010

Choose the method that suits your project's requirements and whether you want to rely on external libraries or implement your own solution.

Comments