Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Format Date and Time in JavaScript

Format dates in JavaScript as YYYY-MM-DD, DD/MM/YYYY and DD MMM YYYY, show relative time like "1 hours ago", and use Intl locales. Explanation and output.

BeginnerJavaScript Date and Time ProgramsExample 2 of 10

The sample output was captured with the clock set to 15 January 2024, 10:30:45 UTC. Your run will show your own date, time and time zone.

format-date-and-time.js
1// Method 1: Basic formatting
2function formatDate(date) {
3 const year = date.getFullYear();
4 const month = String(date.getMonth() + 1).padStart(2, '0');
5 const day = String(date.getDate()).padStart(2, '0');
6 return `${year}-${month}-${day}`;
7}
8
9console.log('YYYY-MM-DD:', formatDate(new Date()));
10
11// Method 2: Multiple formats
12function formatDateMultiple(date, format) {
13 const year = date.getFullYear();
14 const month = String(date.getMonth() + 1).padStart(2, '0');
15 const day = String(date.getDate()).padStart(2, '0');
16 const hours = String(date.getHours()).padStart(2, '0');
17 const minutes = String(date.getMinutes()).padStart(2, '0');
18 const seconds = String(date.getSeconds()).padStart(2, '0');
19
20 const formats = {
21 'YYYY-MM-DD': `${year}-${month}-${day}`,
22 'DD/MM/YYYY': `${day}/${month}/${year}`,
23 'MM/DD/YYYY': `${month}/${day}/${year}`,
24 'YYYY-MM-DD HH:mm:ss': `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`,
25 'DD MMM YYYY': `${day} ${getMonthName(date.getMonth())} ${year}`
26 };
27
28 return formats[format] || formatDate(date);
29}
30
31function getMonthName(month) {
32 const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
33 return months[month];
34}
35
36console.log('DD/MM/YYYY:', formatDateMultiple(new Date(), 'DD/MM/YYYY'));
37console.log('DD MMM YYYY:', formatDateMultiple(new Date(), 'DD MMM YYYY'));
38
39// Method 3: Relative time
40function getRelativeTime(date) {
41 const now = new Date();
42 const diff = now - date;
43 const seconds = Math.floor(diff / 1000);
44 const minutes = Math.floor(seconds / 60);
45 const hours = Math.floor(minutes / 60);
46 const days = Math.floor(hours / 24);
47
48 if (seconds < 60) return `${seconds} seconds ago`;
49 if (minutes < 60) return `${minutes} minutes ago`;
50 if (hours < 24) return `${hours} hours ago`;
51 if (days < 7) return `${days} days ago`;
52 return formatDate(date);
53}
54
55console.log('Relative:', getRelativeTime(new Date(Date.now() - 3600000)));
56
57// Method 4: Locale formatting
58const date = new Date();
59console.log('en-US:', date.toLocaleDateString('en-US'));
60console.log('en-GB:', date.toLocaleDateString('en-GB'));
61console.log('de-DE:', date.toLocaleDateString('de-DE'));
62console.log('ja-JP:', date.toLocaleDateString('ja-JP'));
63
64// Method 5: Custom format with Intl
65const formatter = new Intl.DateTimeFormat('en-US', {
66 year: 'numeric',
67 month: 'long',
68 day: 'numeric',
69 weekday: 'long'
70});
71
72console.log('Formatted:', formatter.format(new Date()));

Sample Output

YYYY-MM-DD: 2024-01-15
DD/MM/YYYY: 15/01/2024
DD MMM YYYY: 15 Jan 2024
Relative: 1 hours ago
en-US: 1/15/2024
en-GB: 15/01/2024
de-DE: 15.1.2024
ja-JP: 2024/1/15
Formatted: Monday, January 15, 2024

In this one

  • How to build fixed formats with padStart
  • How one function can support several formats
  • How to show relative time
  • How to format for any locale with Intl.DateTimeFormat

How it works

  1. 1

    formatDate prints 2024-01-15.

  2. 2

    formatDateMultiple prints 15/01/2024 and 15 Jan 2024.

  3. 3

    getRelativeTime gets a date 1 hour back and prints 1 hours ago.

  4. 4

    toLocaleDateString prints four locale styles.

  5. 5

    Intl.DateTimeFormat prints Monday, January 15, 2024.

Edge cases

Singular units

"1 hours ago" reads badly.

Add a check: value === 1 ? "hour" : "hours". Intl.RelativeTimeFormat also handles this.

Future dates in relative time

A future date gives negative seconds and prints "-30 seconds ago".

Check if diff is negative and say "in 30 seconds" instead.

Locale data missing

A minimal Node build may format every locale like en-US.

Use full ICU (the default in modern Node) or test in a browser.

What's going on

A Date object is not friendly to read. Formatting turns it into text like 15/01/2024 or Monday, January 15, 2024. Each country prefers a different pattern, so formatting is something you will do in every app that shows dates, like an exam timetable or a fee receipt.

Method 1 builds YYYY-MM-DD, the ISO style that sorts correctly as text. It reads the year, month and day, adds 1 to the 0-based month, and pads month and day with padStart so 1 becomes 01.

Method 2 supports several patterns from one function. It builds an object where each key is a format name and each value is the finished string. DD/MM/YYYY is the European and Indian style. MM/DD/YYYY is the US style. DD MMM YYYY uses a short month name from getMonthName. If you ask for an unknown format, it falls back to YYYY-MM-DD. The same date 01/02/2024 means 1 February in India and 2 January in the US, so always label or choose the format on purpose.

Method 3 shows relative time, like "5 minutes ago". It subtracts the date from now to get milliseconds, then converts to seconds, minutes, hours and days. It returns the first unit that fits. After 7 days it falls back to a full date. The output says "1 hours ago" because the code does not handle singular words. A small check for 1 would fix that.

Method 4 uses toLocaleDateString with a locale code. en-US, en-GB, de-DE and ja-JP each give their own style.

Method 5 uses Intl.DateTimeFormat for full control: long weekday, long month, numeric day and year. Intl is the built-in internationalisation API. Best practices: use Intl for locales, handle time zones, format consistently, and respect the user's locale.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What does String(7).padStart(2, '0') return?

Pick an answer to check it.

Question 2

Which locale code gives 15/01/2024?

Pick an answer to check it.

Questions people ask

Which format should I store?

Store ISO (toISOString). Format only when you display.

What is a locale?

A language and region code like en-IN that controls how dates and numbers look.

Is there a built-in "time ago"?

Intl.RelativeTimeFormat formats the words, but you still compute the difference.