Web Development Pro | Lesson 039 | Dates, Times, and International Formatting
Web Development Pro · Lesson 39 of 60
Module 4: Data, modules, and state
In this lesson
Prerequisites and learning outcomes
Complete lesson 38 first. This lesson builds on instants, date-only values, and intl. By the end, you can present dates and prices without silently changing their intended meaning. Plan 10–15 minutes for the core explanation and additional time for the worked practice.
Separate an instant from a calendar date
A workshop may begin at a specific instant, while a planning note may refer only to a calendar date. These are different data types in the task, even if both are stored as strings. An instant needs enough timezone information to identify a moment. A date-only value describes a day without necessarily identifying midnight in the viewer's timezone.
Confusing them can move an event to the previous day for some visitors. For example, parsing a date-only string as an instant and then formatting it in a negative UTC offset can display an earlier calendar date. Preserve the intended meaning before choosing an API or display format.
Format instants with an explicit display timezone
Intl.DateTimeFormat formats dates according to a locale and options. The helper below requires a timestamp ending in Z or an explicit numeric offset, checks whether Date can represent it, and formats it in a chosen timezone. Its input contract is a well-formed timestamp from a validated source; the suffix check alone is not a complete timestamp-schema validator.
File formatting.mjs, instant helper:
export function formatInstant(value, locale = 'en-GB', timeZone = 'UTC') {
if (typeof value !== 'string' || !/(Z|[+-]\d{2}:\d{2})$/.test(value)) {
throw new Error('An explicit timestamp offset is required.');
}
const date = new Date(value);
if (!Number.isFinite(date.getTime())) throw new Error('Invalid instant.');
return new Intl.DateTimeFormat(locale, {
dateStyle: 'medium', timeStyle: 'short', timeZone
}).format(date);
}
For a venue-based event, display the venue timezone and label it. For a remote event, you might also provide the viewer's local time, clearly identified. Do not show an unlabeled 10:00 when visitors could reasonably interpret different zones. Daylight-saving rules can change offsets over the year, so an IANA zone such as Europe/London is often more meaningful than assuming one fixed offset forever.
Preserve a date-only value
The date-only helper validates a YYYY-MM-DD shape, checks that conversion round-trips to the same calendar date, and formats in UTC deliberately to preserve that date. It does not pretend the original value was a user-local appointment instant. The UTC construction is an implementation technique for this display contract.
export function formatDateOnly(value, locale = 'en-GB') {
if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value)) throw new Error('Invalid date shape.');
const date = new Date(`${value}T00:00:00Z`);
if (!Number.isFinite(date.getTime()) || date.toISOString().slice(0, 10) !== value) throw new Error('Invalid calendar date.');
return new Intl.DateTimeFormat(locale, { dateStyle: 'long', timeZone: 'UTC' }).format(date);
}
The round-trip check catches values such as an impossible February day that might otherwise normalize into another month. Always check validity before calling toISOString, which throws for an invalid Date. A real application's permitted year range should also match its requirements rather than accepting every representable historical year by accident.
Format a currency without inventing arithmetic precision
The workshop demo can display a fictional materials amount in British pounds. Store the amount as an integer from zero through 1,000,000 pence (£10,000) under this deliberately bounded demo contract, then format it with Intl.NumberFormat. This is a presentation example, not a payment calculation system. Different currencies have different minor-unit conventions, so do not generalize division by one hundred to every currency.
export function formatPence(pence, locale = 'en-GB') {
if (!Number.isSafeInteger(pence) || pence < 0 || pence > 1000000) throw new Error('Expected integer pence from 0 to 1000000.');
return new Intl.NumberFormat(locale, { style: 'currency', currency: 'GBP' }).format(pence / 100);
}
The helper accepts 1500 and displays £15.00 under the selected locale. It rejects fractional pence and values above the demo limit rather than rounding silently. A safe integer count alone does not guarantee penny precision after division by 100 at extremely large magnitudes; this modest range avoids that boundary. If a product needs taxes, exchange rates, or high-precision financial operations, it needs a carefully defined arithmetic and rounding policy beyond this formatting lesson.
Keep machine values separate from display strings
A localized date string is for people, not a reliable serialization format to parse back later. Keep the original machine-readable value in your data and, where useful, a time element's datetime attribute. The displayed text can change with locale without changing the underlying event moment.
Similarly, do not parse a formatted currency string by removing one symbol and calling Number. Thousands separators, decimal separators, spaces, and symbol placement vary by locale. Preserve the numeric amount separately and use formatting only at the output boundary.
Intl results can vary in punctuation and localized wording across runtime locale-data versions. Tests should assert the important date parts or explicitly document a chosen runtime when exact full-string snapshots are needed. A test that fails only because of a punctuation change is different from one that reveals the wrong day or hour.
Test boundaries and timezone meaning
The tests cover a valid instant, an invalid date, a timestamp without an offset, a leap-day date-only value, an impossible calendar date, and invalid money inputs. They compare important formatted date parts in UTC and another timezone to show that one instant can have different local representations.
These tests use the actual Node Intl implementation and its timezone data. They do not prove every browser has identical locale data or that the source event's timezone was correctly recorded. Verify the browser display and the real event specification separately when building a production schedule.
Worked practice
Worked exercise 1: Avoid a date shift
Task: A date-only workshop day displays as the previous day for a visitor west of UTC. Worked answer: preserve the date-only contract and format it without converting it into the visitor's local instant. Use the date-only helper rather than treating midnight UTC as the event time.
Worked exercise 2: Label an instant
Task: A page shows 10:00 for a remote audience without a timezone. Worked answer: show the chosen timezone or provide clearly labeled venue and viewer-local representations. The same instant can have different clock times, so the display must explain its frame of reference.
Worked exercise 3: Reject fractional pence
Task: The amount is 1500.5 pence. Worked answer: reject it under the integer-pence contract rather than silently formatting an unexplained rounding choice. Decide the arithmetic policy before producing a financial-looking display.
Knowledge check
Question 1
What distinguishes a date-only value from an instant? A) It describes a calendar day without necessarily identifying a moment. B) It is always the viewer's midnight. C) It always includes an offset. D) It can safely be converted through every timezone without change.
Check question 1: answer and explanation
Answer: A. The task's meaning determines the representation and display strategy.
Question 2
Why specify timeZone when formatting a venue event? A) To validate the event's truth. B) To make the display frame explicit and stable. C) To remove daylight-saving rules. D) To change the source timestamp.
Check question 2: answer and explanation
Answer: B. Formatting should use a deliberate timezone rather than an accidental environment default.
Question 3
Why round-trip the date-only value? A) To accept any date string the runtime can parse. B) To turn a normalized impossible day into a valid intended appointment. C) To detect impossible dates that normalize differently. D) To validate only the shape while allowing changed calendar components.
Check question 3: answer and explanation
Answer: C. The calendar components must remain the intended date.
Question 4
Can division by 100 be assumed for every currency? A) Yes, every currency has two minor digits. B) Yes, if Intl is used. C) Yes, for integer inputs. D) No; this helper explicitly uses GBP pence.
Check question 4: answer and explanation
Answer: D. Currency-specific unit conventions must be part of the contract.
Question 5
What should application logic retain alongside localized display text? A) The original machine-readable value. B) Only the localized date string to parse again after reload. C) Only the current numeric offset instead of the event timestamp. D) A display string with separators removed for storage.
Check question 5: answer and explanation
Answer: A. Display formatting should not become the application's storage or parsing format.