Format dates in various common formats
Quick Answer
Extract year, month (zero-padded), and day from a `Date` object and concatenate them in the desired order — no library needed for the three most common formats.
1const formatDate = (date, format = 'YYYY-MM-DD') => {
2 const d = new Date(date);
3 const year = d.getFullYear();
4 const month = String(d.getMonth() + 1).padStart(2, '0');
5 const day = String(d.getDate()).padStart(2, '0');
6
7 const formats = {
8 'YYYY-MM-DD': `${year}-${month}-${day}`,
9 'DD/MM/YYYY': `${day}/${month}/${year}`,
10 'MM/DD/YYYY': `${month}/${day}/${year}`,
11 };
12
13 return formats[format] || formats['YYYY-MM-DD'];
14};The native Date object provides all the parts needed to format dates without a library. This function extracts year, month, and day with zero-padding and maps them to common format strings. For more complex formatting requirements in larger projects, consider the Intl.DateTimeFormat API for locale-aware output.
For simple formatting, the native Date object is sufficient. For complex operations like date arithmetic, time zones, or relative formatting (e.g. '3 days ago'), use `date-fns` (tree-shakeable) or `dayjs` (tiny bundle).
This free javascript code snippet for date formatting is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this beginner-level example will help you implement date formatting quickly and correctly.
All snippets in the Snippetly library follow javascript best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses javascript.
Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.