jsrosetta

Standard library

Date and Time

Node.js's Date and Intl.DateTimeFormat compared to Go's immutable time.Time, Rust's chrono, Swift's Date, and Java's java.time: parsing, adding days, and formatting.

Minimum versions
Node.js ≥ 12.20Go ≥ 1.20Rust ≥ 1.62Swift ≥ 5.5Java ≥ 25
Verified on
Node.js 24.12.0Go 1.27.1Rust 1.98.1Swift 6.2.4Java 25.0.4.1

Node.js code is an ES module: save it as .mjs or set "type": "module" in package.json.

Node.js represents a point in time with Date — an object you can mutate through set* methods. Go uses time.Time, an immutable struct: every add/subtract operation returns a new time.Time value instead of changing it in place. Rust's std has no calendar-aware date type at all, so it needs an external crate (chrono). Swift uses Foundation's Date (a plain instant) together with Calendar for calendar-based arithmetic. Java uses java.time, immutable just like Go's. Formatting differs across the board too: Node.js and Java use named fields/patterns, Go uses a "reference date" (2006-01-02) as its layout, Rust uses strftime-style specifiers, and Swift uses FormatStyle — a chainable builder (.dateTime.year().month()...) — not strftime.

Parsing, adding days, and formatting

const nowUnix = Date.now() // milliseconds since the epoch
console.log(nowUnix)
 
const datestr = '2019-01-17T09:24:23+00:00'
const date = new Date(datestr)
console.log(date.getTime()) // milliseconds
console.log(date.toString()) // in the machine's local timezone
 
const futureDate = new Date(date)
futureDate.setDate(date.getDate() + 14) // mutates in place
console.log(futureDate.toString())
 
const formatted = new Intl.DateTimeFormat('en-US', {
  year: 'numeric',
  month: '2-digit',
  day: '2-digit',
}).format(date)
console.log(formatted) // 01/17/2019
# first line is the current timestamp (non-deterministic); the date strings
# depend on the machine's local timezone (this was run with TZ=Asia/Saigon)
$ node datetime.js
1790530769893
1547717063000
Thu Jan 17 2019 16:24:23 GMT+0700 (Indochina Time)
Thu Jan 31 2019 16:24:23 GMT+0700 (Indochina Time)
01/17/2019
 
$ go run datetime.go
1790530770
1547717063
2019-01-17 09:24:23 +0000 +0000
2019-01-31 09:24:23 +0000 +0000
2019-01-31
01/17/2019
 
$ cargo run -q
1790532152
1547717063
2019-01-17 09:24:23 +00:00
2019-01-31 09:24:23 +00:00
01/17/2019
 
$ swift main.swift
1790532172
1547717063
2019-01-17 09:24:23 +0000
2019-01-31 09:24:23 +0000
01/17/2019
 
$ java Main.java
1790532161
1547717063
2019-01-17T09:24:23Z
2019-01-31T09:24:23Z
01/17/2019

Reference: github.com/miguelmota/golang-for-nodejs-developers#datetime