Dates show up everywhere in apps: posts, events, logs, deadlines.
In this lesson you will learn how to work with dates and how to design small reusable date utilities.
By the end of this lesson you should be able to:
- Create and parse dates in JavaScript
- Format dates for display
- Compare and sort dates
- Perform basic date arithmetic
- Recognize common date pitfalls
- Design reusable date utility functions
- How would you sort blog posts by date?
- How would you display "2 days ago"?
- How would you format this:
2026-04-02T19:52:00Z?
Dates are:
- everywhere
- easy to misuse
- a great example of a library problem
const now = new Date()
const fromString = new Date('2025-12-25')
const fromNumbers = new Date(2025, 11, 25) // Dec (month is 0-indexed!)
const timestamp = Date.now() // number (ms since 1970)- Months are 0-indexed in numeric constructor
- Strings are usually ISO format
- What is the difference between
Date.now()andnew Date()? - What month is
11?
const d = new Date()
d.toLocaleString()
d.toDateString()
d.toISOString()new Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric'
}).format(new Date())When writing a library function:
- Should you return a
Date? - A formatted string?
- A number (timestamp)?
👉 Formatting is usually for display, not storage.
const d1 = new Date('2025-01-01')
const d2 = new Date('2025-12-25')
console.log(d1 < d2) // truedates.sort((a, b) => a - b)posts.sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt))Write a sort function that sorts posts newest first.
const d1 = new Date('2025-01-01')
const d2 = new Date('2025-01-10')
const diffMs = d2 - d1const days = diffMs / (1000 * 60 * 60 * 24)- Should you round, floor, or ceil?
- What counts as "1 day ago"?
👉 These are design decisions in a library
- Months are 0-indexed (numeric constructor)
- Invalid dates (
new Date('bad')) - Time zones (local vs UTC)
- String parsing inconsistencies
new Date('2025-12-25')
new Date(2025, 11, 25)👉 These may not behave exactly the same
Design 2–3 date utility functions.
Examples:
formatDate(dateString)daysBetween(a, b)isBefore(a, b)relativeDate(dateString)
For each function define:
- Input
- Output
- Behavior
- Edge cases
👉 Be precise. Ambiguous behavior leads to bugs.
You will complete a GitHub Classroom assignment with date problems.
https://classroom.github.com/a/hgeSh6Hb
- Write small reusable date functions
- Practice working with Date objects
- Apply API design thinking
- Format a date
- Compare two dates
- Calculate days between dates
- Sort posts by date
- Generate "x days ago" labels
Write answers:
- What makes working with dates difficult?
- What is one common pitfall?
- What should a good date utility function define clearly?
Dates are not just values.
They are behavior + assumptions.
Good libraries make those assumptions explicit.