JavaScript Date & Time Cheat Sheet

Create a New Date

const now = new Date();
const specificDate = new Date('2025-04-05T12:00:00');

Get Date Parts

const date = new Date();
date.getFullYear(); // 2025
date.getMonth(); // 0-11 (January is 0)
date.getDate(); // Day of month
date.getDay(); // 0-6 (Sunday is 0)
date.getHours();
date.getMinutes();
date.getSeconds();

Format Date (Manual)

const date = new Date();
const formatted = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;

Format with Intl.DateTimeFormat

const formatter = new Intl.DateTimeFormat('en-US', {
  dateStyle: 'full',
  timeStyle: 'short'
});
formatter.format(new Date());
// Example: "Saturday, April 5, 2025 at 12:30 PM"

Add/Subtract Days

const addDays = (date, days) => {
  const copy = new Date(date);
  copy.setDate(copy.getDate() + days);
  return copy;
};

Compare Dates

const isBefore = (a, b) => new Date(a) < new Date(b);
const isSameDay = (a, b) =>
  new Date(a).toDateString() === new Date(b).toDateString();

Get Timezone Offset

const offsetMinutes = new Date().getTimezoneOffset();
// In minutes (e.g., -420 for PDT)

Convert to ISO String

new Date().toISOString();
// Example: "2025-04-05T19:34:00.000Z"

Parse ISO String

const date = new Date("2025-04-05T19:34:00.000Z");

Time Since (e.g., “5 minutes ago”)

const timeSince = date => {
  const seconds = Math.floor((new Date() - new Date(date)) / 1000);
  if (seconds < 60) return `${seconds} sec ago`;
  const minutes = Math.floor(seconds / 60);
  if (minutes < 60) return `${minutes} min ago`;
  const hours = Math.floor(minutes / 60);
  if (hours < 24) return `${hours} hrs ago`;
  const days = Math.floor(hours / 24);
  return `${days} days ago`;
};