JavaScript and TypeScript course ยท Module 5: Advanced JavaScript
Date Object and Time Manipulation
In this lesson7
At the Jurassic Park command center, Ray Arnold monitors the dinosaur feeding schedules. "Time is a key element of safety," he explains. "I need to know exactly when each dinosaur was fed, when the next feeding is due, and how much time has passed since the last fence inspection." Time in JavaScript can surprise you, though: June has the number 5 here, and the same date written in two ways can point to different hours. Let's defuse these traps one by one.
Creating Date Objects
You create a Date object with the new Date() constructor. Without arguments you get the current moment, and with numbers a specific date made of a year, month and day:
// Current date and time
const now = new Date();
console.log(now); // e.g. "Sat Jun 15 2024 14:30:00 GMT+0200"
// From a specific date (note: months start at 0!)
const jurassicOpening = new Date(1993, 5, 11); // June 11, 1993
console.log(jurassicOpening);
// From a full date and time
const incident = new Date(1993, 5, 11, 20, 30, 0);
// June 11, 1993, 20:30:00Notice the five: months are counted from zero, so January is 0 and June is 5. Days of the month are counted normally, from 1. This is the most common Date trap.
You can also recreate a date from text or from a number of milliseconds, a timestamp:
// From a string (ISO 8601)
const dateFromString = new Date("2024-06-15T14:30:00");
// A date without a time is treated as UTC!
const dateOnly = new Date("2024-06-15");
// From a timestamp (milliseconds since January 1, 1970)
const fromTimestamp = new Date(1718451000000);
const epoch = new Date(0); // January 1, 1970, 00:00:00 UTC
// Timestamp of the current moment
const timestamp = Date.now();
console.log(timestamp); // e.g. 1718451000000Text with a date and time but no time zone is read as local time, while a date alone is read as midnight UTC. In Central Europe dateOnly will therefore show 1 or 2 a.m., depending on the season. Date.now() returns the number of milliseconds since January 1, 1970, not a Date object.
Getters - Extracting Date Components
Once a date exists, the get... methods extract single components from it - the year, month, day or hour:
const feedingTime = new Date("2024-06-15T08:30:00");
// Extracting components
console.log(feedingTime.getFullYear()); // 2024
console.log(feedingTime.getMonth()); // 5 (June - months start at 0!)
console.log(feedingTime.getDate()); // 15 (day of the month)
console.log(feedingTime.getDay()); // 6 (Saturday - days start at 0, Sunday = 0)
console.log(feedingTime.getHours()); // 8
console.log(feedingTime.getMinutes()); // 30
console.log(feedingTime.getSeconds()); // 0
console.log(feedingTime.getMilliseconds()); // 0
// Timestamp
console.log(feedingTime.getTime()); // milliseconds since 1970
// UTC versions
console.log(feedingTime.getUTCHours()); // the hour in UTCgetDate() returns the day of the month, and getDay() the day of the week counted from Sunday as 0 - they are easy to confuse. The methods work in the computer's time zone, and the versions with UTC in the name in universal time.
Setters - Modifying Dates
The set... methods work the other way round and change the date in place, because a Date object is mutable:
const nextFeeding = new Date();
// Setting components
nextFeeding.setFullYear(2024);
nextFeeding.setMonth(6); // July (months start at 0!)
nextFeeding.setDate(20);
nextFeeding.setHours(9);
nextFeeding.setMinutes(0);
nextFeeding.setSeconds(0);
// Setting several at once
nextFeeding.setFullYear(2024, 6, 20); // year, month, day
console.log(nextFeeding);setFullYear() accepts the year, month and day at once. Setters carry the overflow over by themselves: setDate(32) in June gives July 2, and adding hours with setHours() moves past midnight into the next day.
Formatting Dates
Built-in Methods
To display a date, the Date object has several ready-made methods. Some give a fixed format, and some depend on the language settings:
const event = new Date("2024-06-15T14:30:00");
// Different formats
console.log(event.toString());
// "Sat Jun 15 2024 14:30:00 GMT+0200 (Central European Summer Time)"
console.log(event.toDateString());
// "Sat Jun 15 2024"
console.log(event.toTimeString());
// "14:30:00 GMT+0200 (Central European Summer Time)"
console.log(event.toISOString());
// "2024-06-15T12:30:00.000Z" (UTC)
console.log(event.toLocaleDateString());
// "6/15/2024" (depends on the locale)
console.log(event.toLocaleTimeString());
// "2:30:00 PM" (depends on the locale)
console.log(event.toLocaleString());
// "6/15/2024, 2:30:00 PM"toISOString() always gives UTC time, which is why 14:30 in a Central European summer becomes 12:30 with the letter Z. The results of the toLocale... methods depend on the browser's language - the comments show US English settings.
Intl.DateTimeFormat - Advanced Formatting
Full control over the format comes from Intl.DateTimeFormat. You pass a language and options, and the formatter takes care of the names of days and months:
const date = new Date("2024-06-15T14:30:00");
// US English format
const usFormatter = new Intl.DateTimeFormat('en-US', {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric'
});
console.log(usFormatter.format(date));
// "Saturday, June 15, 2024"
// Format with time
const fullFormatter = new Intl.DateTimeFormat('en-US', {
dateStyle: 'full',
timeStyle: 'short'
});
console.log(fullFormatter.format(date));
// "Saturday, June 15, 2024 at 2:30 PM"
// Short format
const shortFormatter = new Intl.DateTimeFormat('en-US', {
dateStyle: 'short'
});
console.log(shortFormatter.format(date));
// "6/15/24"
// Shorthand: toLocaleDateString() accepts the same options
console.log(date.toLocaleDateString('en-US', { weekday: 'long' }));
// "Saturday"You create a formatter once and reuse it. dateStyle and timeStyle are ready-made option sets, and toLocaleDateString() accepts the same options for a one-off format.
Date Calculations
Difference Between Dates
Subtracting two dates gives a number of milliseconds, because JavaScript converts each date to its timestamp:
const lastFeeding = new Date("2024-06-15T08:00:00");
const now = new Date("2024-06-15T14:30:00");
// Difference in milliseconds
const diffMs = now - lastFeeding;
console.log(diffMs); // 23400000
// Conversion to different units
const diffSeconds = diffMs / 1000;
const diffMinutes = diffMs / (1000 * 60);
const diffHours = diffMs / (1000 * 60 * 60);
const diffDays = diffMs / (1000 * 60 * 60 * 24);
console.log(`Last fed ${diffHours} hours ago`);
// "Last fed 6.5 hours ago"
// Comparisons: < and > work, === compares objects
console.log(lastFeeding < now); // true
console.log(new Date("2024-06-15T08:00:00") === lastFeeding); // false
console.log(new Date("2024-06-15T08:00:00").getTime() === lastFeeding.getTime()); // trueDividing by 1000, 60 and 60 turns milliseconds into hours. The < and > operators compare dates correctly, but === checks whether it is the same object - compare separate dates with getTime().
Adding and Subtracting Time
You add time by adding milliseconds to the timestamp or by moving a component with a setter. A helper function wraps both variants in one place:
const baseDate = new Date("2024-06-15T08:00:00");
// Add 3 hours
const plus3Hours = new Date(baseDate.getTime() + 3 * 60 * 60 * 1000);
console.log(plus3Hours.toLocaleTimeString()); // "11:00:00 AM"
// Add 7 days
const plus7Days = new Date(baseDate);
plus7Days.setDate(plus7Days.getDate() + 7);
console.log(plus7Days.toLocaleDateString()); // "6/22/2024"
// Subtract 1 month
const minus1Month = new Date(baseDate);
minus1Month.setMonth(minus1Month.getMonth() - 1);
console.log(minus1Month.toLocaleDateString()); // "5/15/2024"
// Helper function for adding time
function addTime(date, amount, unit) {
const result = new Date(date);
switch(unit) {
case 'seconds':
result.setSeconds(result.getSeconds() + amount);
break;
case 'minutes':
result.setMinutes(result.getMinutes() + amount);
break;
case 'hours':
result.setHours(result.getHours() + amount);
break;
case 'days':
result.setDate(result.getDate() + amount);
break;
case 'months':
result.setMonth(result.getMonth() + amount);
break;
case 'years':
result.setFullYear(result.getFullYear() + amount);
break;
}
return result;
}
console.log(addTime(baseDate, 2, 'hours').toLocaleTimeString()); // "10:00:00 AM"Each example starts from a copy, new Date(baseDate), so baseDate stays untouched. For days and months I recommend setters, because milliseconds know nothing about the daylight saving change, when a day has 23 or 25 hours.
Practical Examples in Jurassic Park
1. Feeding Schedule System
The first scheduler keeps specific feeding times in a Map and calculates how much time is left until the meal:
class FeedingScheduler {
constructor() {
this.schedule = new Map();
}
scheduleFeed(dinoId, feedingTime) {
this.schedule.set(dinoId, {
scheduledTime: new Date(feedingTime),
status: 'pending'
});
}
getNextFeeding(dinoId) {
const feeding = this.schedule.get(dinoId);
if (!feeding) return null;
const now = new Date();
const timeUntil = feeding.scheduledTime - now;
if (timeUntil < 0) {
return { status: 'overdue', overdue: this.formatDuration(-timeUntil) };
}
return {
status: 'scheduled',
timeUntil: this.formatDuration(timeUntil),
scheduledTime: feeding.scheduledTime.toLocaleString('en-US')
};
}
formatDuration(ms) {
const hours = Math.floor(ms / (1000 * 60 * 60));
const minutes = Math.floor((ms % (1000 * 60 * 60)) / (1000 * 60));
if (hours > 0) {
return `${hours}h ${minutes}min`;
}
return `${minutes}min`;
}
}
const scheduler = new FeedingScheduler();
scheduler.scheduleFeed('TREX-001', '2024-06-15T09:00:00');
console.log(scheduler.getNextFeeding('TREX-001'));When the time has passed, the date difference is negative - hence the overdue status, which you will see for the date in the example. formatDuration() breaks milliseconds into hours and minutes with the remainder operator %.
2. A Schedule Every Few Hours
The second variant only knows the interval between meals. The next feeding time is the time of the last feeding plus the interval in milliseconds:
class FeedingScheduler {
constructor() {
this.schedules = new Map();
}
addSchedule(dinoId, feedingIntervalHours) {
this.schedules.set(dinoId, {
lastFed: new Date(),
interval: feedingIntervalHours,
nextFeeding: new Date(Date.now() + feedingIntervalHours * 3600000)
});
}
getNextFeeding(dinoId) {
const schedule = this.schedules.get(dinoId);
if (!schedule) return null;
return schedule.nextFeeding;
}
isOverdue(dinoId) {
const schedule = this.schedules.get(dinoId);
if (!schedule) return false;
return new Date() > schedule.nextFeeding;
}
getOverdueDinosaurs() {
const overdue = [];
const now = new Date();
for (const [dinoId, schedule] of this.schedules) {
if (now > schedule.nextFeeding) {
const overdueHours = (now - schedule.nextFeeding) / 3600000;
overdue.push({
dinoId,
overdueBy: `${overdueHours.toFixed(1)} hours`,
nextFeeding: schedule.nextFeeding
});
}
}
// The dinosaur waiting longest goes first
return overdue.sort((a, b) => a.nextFeeding - b.nextFeeding);
}
recordFeeding(dinoId) {
const schedule = this.schedules.get(dinoId);
if (!schedule) return false;
const now = new Date();
schedule.lastFed = now;
schedule.nextFeeding = new Date(now.getTime() + schedule.interval * 3600000);
console.log(`${dinoId} fed at ${now.toLocaleTimeString()}. Next feeding: ${schedule.nextFeeding.toLocaleTimeString()}`);
return true;
}
}isOverdue() compares dates with a plain >, and getOverdueDinosaurs() walks the map with a for...of loop and sorts the result so that those waiting longest come first. recordFeeding() starts a new interval from the moment of feeding.
Each species gets its own feeding rhythm:
// Usage
const scheduler = new FeedingScheduler();
scheduler.addSchedule("TREX-001", 8); // T-Rex every 8 hours
scheduler.addSchedule("RAPTOR-01", 6); // Raptor every 6 hours
scheduler.addSchedule("BRACHIOSAURUS", 4); // Herbivore every 4 hours
const overdue = scheduler.getOverdueDinosaurs();
if (overdue.length > 0) {
console.log("Overdue feedings:", overdue);
}Right after they are added nobody is overdue, so nothing is printed - delays appear once an interval passes without recordFeeding().
3. Relative Time Formatting
Visitors don't care about a timestamp, only about a message like "5 minutes ago". You can calculate it by hand or hand the job over to Intl.RelativeTimeFormat:
function formatRelativeTime(date) {
const now = new Date();
const diff = now - new Date(date);
const seconds = Math.floor(diff / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
if (seconds < 60) return 'just now';
if (minutes < 60) return `${minutes} min ago`;
if (hours < 24) return `${hours} h ago`;
if (days < 7) return `${days} days ago`;
return new Date(date).toLocaleDateString('en-US');
}
// Or using Intl.RelativeTimeFormat
function formatRelativeTimeIntl(date) {
const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
const diff = new Date(date) - new Date();
const seconds = Math.round(diff / 1000);
const minutes = Math.round(seconds / 60);
const hours = Math.round(minutes / 60);
const days = Math.round(hours / 24);
if (Math.abs(seconds) < 60) return rtf.format(seconds, 'second');
if (Math.abs(minutes) < 60) return rtf.format(minutes, 'minute');
if (Math.abs(hours) < 24) return rtf.format(hours, 'hour');
return rtf.format(days, 'day');
}
console.log(formatRelativeTime(new Date(Date.now() - 3600000))); // "1 h ago"
// The formatter itself: numeric: 'auto' turns numbers into words
const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
console.log(rtf.format(-1, 'day')); // "yesterday"
console.log(rtf.format(-3, 'hour')); // "3 hours ago"
console.log(rtf.format(2, 'day')); // "in 2 days"
console.log(rtf.format(1, 'week')); // "next week"The hand-written version knows only one language and rigid endings, while Intl.RelativeTimeFormat handles grammar by itself. The numeric: 'auto' option turns minus one day into "yesterday" and one week ahead into "next week".
Summary
Ray Arnold wraps up the training: "In critical systems like Jurassic Park, precise time management is a matter of life and death. Remember:"
- Months start at 0 - January is 0, December is 11
- Use ISO 8601 to store dates ("2024-06-15T14:30:00Z")
- Intl.DateTimeFormat for internationalization
- Avoid string manipulation - use Date methods
- Consider libraries (date-fns, dayjs) for complex operations
My advice: store dates in UTC and convert them to local time only when displaying them. A new API called Temporal is also on its way, designed as a full replacement for Date - before you reach for it, check its support on MDN. In the next lesson you will save data in localStorage, where dates come back as plain strings.
Remember: the park clock counts months from zero and time in milliseconds - keep an eye on both, and no dinosaur will miss a feeding.
Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What does Date.now() return in JavaScript?
2. What is the important gotcha when working with months in the Date object?
Hands-on tasks in the game
- Code editor
Create a feeding schedule that calculates the next feeding time and checks for delays.