Back to library
🛠️Utilitiesjavascriptbeginner

Format Date

Utility functions for date formatting

datesformattingutilities

Code

1// Format date to readable string
2function formatDate(date, format = 'full') {
3  const d = new Date(date);
4  
5  const formats = {
6    full: d.toLocaleDateString('en-US', {
7      year: 'numeric',
8      month: 'long',
9      day: 'numeric'
10    }),
11    short: d.toLocaleDateString('en-US', {
12      year: 'numeric',
13      month: 'short',
14      day: 'numeric'
15    }),
16    numeric: d.toLocaleDateString('en-US'),
17    time: d.toLocaleTimeString('en-US', {
18      hour: '2-digit',
19      minute: '2-digit'
20    }),
21    datetime: d.toLocaleString('en-US', {
22      year: 'numeric',
23      month: 'short',
24      day: 'numeric',
25      hour: '2-digit',
26      minute: '2-digit'
27    }),
28    iso: d.toISOString(),
29    relative: getRelativeTime(d)
30  };
31  
32  return formats[format] || formats.full;
33}
34
35// Get relative time (e.g., "2 hours ago")
36function getRelativeTime(date) {
37  const now = new Date();
38  const diff = now - new Date(date);
39  const seconds = Math.floor(diff / 1000);
40  const minutes = Math.floor(seconds / 60);
41  const hours = Math.floor(minutes / 60);
42  const days = Math.floor(hours / 24);
43  
44  if (days > 0) return `${days} day${days > 1 ? 's' : ''} ago`;
45  if (hours > 0) return `${hours} hour${hours > 1 ? 's' : ''} ago`;
46  if (minutes > 0) return `${minutes} minute${minutes > 1 ? 's' : ''} ago`;
47  return 'Just now';
48}
49
50// Usage examples
51console.log(formatDate(new Date(), 'full')); // "January 15, 2024"
52console.log(formatDate(new Date(), 'relative')); // "Just now"

Quick Tips

  • Click the "Copy" button to copy the code to your clipboard
  • This code is production-ready and can be used in your projects
  • Check out related snippets below for more examples

Build Your Own Snippet Library

Organize your team's code snippets with Snippetly. Share knowledge and boost productivity across your organization.