How do I format a date in JavaScript?
How can you easily format dates in JavaScript to match your preferred style? What are the built-in methods and libraries available to help you convert and display dates effectively?
Formatting a date in JavaScript can be simple or a bit tricky, depending on the format you need. Here's how you can do it:
Using toLocaleDateString()
This method is great for quick, readable formats based on the user's locale.
Example:
const date = new Date();
console.log(date.toLocaleDateString()); // Output: e.g., "4/9/2025"
Custom formatting with getFullYear(), getMonth(), and getDate()
If you need a specific format like YYYY-MM-DD, you can manually build it:
const date = new Date();
const formattedDate = `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
console.log(formattedDate); // Output: "2025-04-09"
Using libraries like date-fns or moment.js
These make formatting way easier and cleaner:
// Using date-fns
import { format } from 'date-fns';
console.log(format(new Date(), 'yyyy-MM-dd')); // Output: "2025-04-09"
Note: moment.js is now in maintenance mode, so libraries like date-fns or dayjs are preferred for new projects.
ISO format
If you need a standard format, toISOString() gives you that:
console.log(new Date().toISOString()); // Output: "2025-04-09T12:00:00.000Z"
In short, JavaScript gives you multiple ways to format a date—built-in methods for simple needs, and libraries for more control and cleaner code. Choose based on your use case and project size.