Mastering Time in JavaScript: From Unix Timestamps to Modern Date Libraries
This article explains the history of global time standards, how computers represent time with Unix timestamps and the 2038 problem, details ISO 8601 and RFC 2822 formats, and provides practical JavaScript Date usage examples along with comparisons of popular date‑handling libraries such as Moment.js, Dayjs, and Miment.
Background and Basic Concepts
Historically, local times varied worldwide until the 1884 International Meridian Conference established Greenwich as the prime meridian, defining 24 time zones each 15° of longitude apart. Standard time concepts include GMT (Greenwich Mean Time), IAT (International Atomic Time), and UTC (Coordinated Universal Time), with leap seconds added to keep UTC within 0.9 seconds of UT1.
Standard Time
GMT – the original astronomical time reference based on the Sun crossing Greenwich at noon.
IAT – International Atomic Time, derived from atomic clocks and accurate to nanoseconds.
UTC – a version of world time that adjusts GMT with leap seconds; UTC and GMT are generally considered equivalent.
Time Zones
Local time = UTC + offset (e.g., Beijing = UTC+8).
DST (Daylight Saving Time) adds one hour during summer in many regions.
Time Representation in Computers
Unix systems store time as a 32‑bit signed integer counting seconds since 1970‑01‑01 00:00:00 UTC, known as the Unix epoch.
Timestamp
Unix time (seconds) – seconds elapsed since the epoch.
Timestamp (milliseconds) – milliseconds elapsed since the epoch.
2038 Problem
On 32‑bit systems the maximum time_t value (0x7fffffff) corresponds to 2038‑01‑19 03:14:07. After that the value overflows to a negative number, causing the system clock to roll back to 1901 and breaking software.
The simplest fix is to use a 64‑bit time_t, which extends the range billions of years into the future; most modern OSes already do, but many embedded 32‑bit devices remain vulnerable.
ISO 8601 and RFC 2822
ISO 8601
Uses only numbers and a few symbols ("-", ":", "T", "Z").
Fixed‑width fields with leading zeros.
24‑hour clock, e.g. 2018-07-03T22:44:26Z or 20180703T224426Z.
RFC 2822
Common in HTTP and email headers, e.g. Wed 01 Jun 2016 14:31:46 -0700.
Time in Front‑End Development
Back‑ends typically return timestamps in seconds or milliseconds; front‑ends display dates in many formats such as "2021‑01‑25", "2021/01/25", "2021年01月25日", or "2021年01月25日 12:35:10".
JavaScript handles dates with the built‑in Date object. var now = new Date(); Key methods include:
Constructors: new Date(), new Date('2020‑01‑01'), new Date(2020,0,1,12,30,45), new Date(milliseconds).
Parsing: Date.parse('May 25,2004') returns a millisecond timestamp.
Current timestamp: Date.now().
Getters/Setters: getFullYear(), getMonth(), getDate(), getHours(), getMinutes(), getSeconds(), getMilliseconds(), getTime(), and their UTC counterparts.
Conversion methods: toString(), toISOString(), toLocaleString(), valueOf() (returns milliseconds).
Common Scenarios
Days in a Month
function getDaysInMonth(year, month) {
let temp = new Date(year, month, 0);
return temp.getDate();
}
// 2019,2 → 28
// 2020,2 → 29Generate Last 7 Days
let now = new Date();
let s = '';
let i = 0;
while (i < 7) {
s += now.getFullYear() + '/' + (now.getMonth()+1) + '/' + now.getDate() + '
';
now = new Date(now - 24*60*60*1000);
i++;
}
console.log(s);Custom Format Function
Date.prototype.Format = function(fmt) {
const o = {
"M+": this.getMonth()+1,
"D+": this.getDate(),
"H+": this.getHours(),
"m+": this.getMinutes(),
"s+": this.getSeconds(),
"q+": Math.floor((this.getMonth()+3)/3),
"S" : this.getMilliseconds()
};
if (/(Y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4-RegExp.$1.length));
}
for (let k in o) {
if (new RegExp('('+k+')').test(fmt)) {
fmt = fmt.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : ("00"+o[k]).substr((""+o[k]).length));
}
}
return fmt;
};
let date = new Date();
date.Format('YYYY-MM-DD HH:mm:ss');Practical Date Libraries – Moment, Dayjs, Miment
All three provide similar APIs for parsing, formatting, and manipulating dates. Moment.js is large (≈280 kB) and mutable; Dayjs is a tiny (≈2 kB) immutable alternative; Miment is an even smaller (≈1 kB) library.
Moment.js Status
Moment is now in maintenance mode. Its drawbacks are mutable objects that can cause bugs and a large bundle size, especially when timezone data is included.
Alternatives
Native Date and Intl for simple needs.
Temporal (TC39 proposal) – a future built‑in API for dates and times.
Dayjs – 2 KB immutable library with a Moment‑compatible API.
Miment – 1 KB library for basic date handling.
Dayjs Example
dayjs().format('YYYY-MM-DD HH:mm:ss'); // 2021-01-26 20:49:36Chainable usage:
dayjs()
.startOf('month')
.add(1, 'day')
.subtract(1, 'year');Dayjs Source Snippet
var isDayjs = d => d instanceof Dayjs;
var wrapper = (date, instance) => dayjs(date, { locale: instance.$L });
var parseDate = function(cfg) {
var date = cfg.date, utc = cfg.utc;
if (date === null) return new Date(NaN);
if (Utils.u(date)) return new Date();
if (date instanceof Date) return new Date(date);
if (typeof date === 'string' && !/Z$/i.test(date)) {
var d = date.match(C.REGEX_PARSE);
if (d) {
var m = d[2] - 1 || 0;
var ms = (d[7] || '0').substring(0,3);
if (utc) {
return new Date(Date.UTC(d[1], m, d[3]||1, d[4]||0, d[5]||0, d[6]||0, ms));
}
return new Date(d[1], m, d[3]||1, d[4]||0, d[5]||0, d[6]||0, ms);
}
}
return new Date(date);
};
var dayjs = (date, c) => {
if (isDayjs(date)) return date.clone();
const cfg = c || {};
cfg.date = date;
return new Dayjs(cfg);
};
var Dayjs = function() {
function Dayjs(cfg) {
this.$L = parseLocale(cfg.locale, null, true);
this.parse(cfg);
}
var _proto = Dayjs.prototype;
_proto.parse = function(cfg) { this.$d = parseDate(cfg); this.init(); };
_proto.init = function() {
var d = this.$d;
this.$y = d.getFullYear();
this.$M = d.getMonth();
this.$D = d.getDate();
this.$W = d.getDay();
this.$H = d.getHours();
this.$m = d.getMinutes();
this.$s = d.getSeconds();
this.$ms = d.getMilliseconds();
};
_proto.clone = function() { return wrapper(this.toDate(), this); };
_proto.toDate = function() { return new Date(this.$d); };
// ... other methods omitted for brevity
return Dayjs;
}();Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
