Notes on JavaScript Date
2025-02-06 | 1 min reading
Quick notes on using Date with JavaScript.
What can you expect when you receive inavlid values from your API?
[OK] new Date(""); Invalid Date
[OK] new Date([]); Invalid Date
[OK] new Date(undefined); Invalid Date
[NO] new Date(null); Thu Jan 01 1970 10:00:00 GMT+1000 (Australian Eastern Standard Time)
You can test for Invalid Date
but if you init with null
you still got troubles.
const invalid = new Date("");
invalid.getDate(); // NaN
if (! invalid.getDate()) {
console.log("invalid")
return;
}
On date formats
There are two possibly format for a date: local time
and UTC
.
- Local
-
Time in a specific locality (timezone).
This is usually + or - some hours from UTC. - Coordinated Universal Time (UTC)
- Time in primary locality (Greenwich, England).
Legend:
YYYY = four-digit year
MM = two-digit month (01=January, etc.)
DD = two-digit day of month (01 through 31)
hh = two digits of hour (00 through 23) (am/pm NOT allowed)
mm = two digits of minute (00 through 59)
ss = two digits of second (00 through 59)
s = one or more digits representing a decimal fraction of a second
TZD = time zone designator (Z or +hh:mm or -hh:mm)
Examples:
// note: my local time is (Australian Eastern Daylight Time)
// Local Time [date only]
// YYYY-MM-DD ~> date with the current local time
// Fri Dec 28 2012 XX:00:00 GMT+1100 (Australian Eastern Daylight Time)
new Date("2012-12-28")
// Local Time [date and time]
// YYYY-MM-DDThh:mm ~> date with time
// Fri Dec 28 2012 18:12:33 GMT+1100 (Australian Eastern Daylight Time)
new Date("2012-12-28T18:12:33")
// Local Time with timezone
// Sat Dec 29 2012 04:12:33 GMT+1100 (Australian Eastern Daylight Time) {}
// day and time get recalculated from +01:00 to +11:00
//
// in particular 2012-12-28T18:12:33+01:00 ~> 2012-12-29T04:12:33+11:00
// this is because:
// +01:00 - +11:00 = +10:00 // so plus 10 hours
// 2012-12-28T18:12:33 + 10 hours ~> 2012-12-29T04:12:33+11:00
//
// in particular for the hours
// 18 + 10 := 24h (18 + 6) + 04 (10 - 6)
new Date("2012-12-28T18:12:33+01:00")
// UTC Time (local time with timezone +0)
// Sat Dec 29 2012 04:12:33 GMT+1100 (Australian Eastern Daylight Time)
new Date("2012-12-28T17:12:33.000Z")
new Date("2012-12-28T17:12:33+00:00")