Vanilla JavaScript date manipulation

You don't need moment.js! Just use few snippets of native JavaScript code to parse and manipulate dates.

Web
JavaScript
Moment.js is used in many projects to parse, validate, manipulate, and display dates and times in JavaScript. There are few alternative libraries which offer similar features but with a lighter weight, for example dayjs. If you need Internationalization and localization probably Moment.js is a good choice.

I attended at DEVit conf in 2017 and had the pleasure to meet substack: he is a very kind person and, in my opinion, one of the most brilliant developer around and main evangelist of the holy Unix phylosophy. Talking about minimalism, vanilla code, etc. he said to me

… also moment.js it is unnecessary, you can achieve the features you need with few lines of code, instead of importing it in your build

I thought it was an interesting point and those words were in background for two years, until now that I decided to write down few snippets I use to manipulate and parse dates in Javascript.

Now

Start from here, now!

const now = new Date()

Current Unix timestamp in seconds

Math.floor(now.getTime() / 1000)

Notice also this syntax is valid if you want to get a value on the fly with no need to create a reference

Math.floor(new Date().getTime() / 1000)

De Mysteriis Dom JavaScript!

Also following snippets are weird but they work, and even more… they work in UTC.

Add or subtract time.

Get yesterday date.

now.setDate(now.getDate() - 1)

Go back two hours.

now.setHours(now.getHours() - 2)

Add one month.

now.setMonth(now.getMonth() + 1)

Get last day of previous month.

now.setDate(1)
now.setDate(now.getDate() - 1)

Date extraction

Get year, month, day, hour, minute, second and millisecond as left padded strings.

const [yyyy, mm, dd, hh, mi, ss, mls] = now.toISOString().split(/[^\d]/)
// ['2018', '07', '16', '12', '01', '15', '107']

Date formats

Convert to YYYY-MM-DD format.

now.toISOString().slice(0, 10)

Truncations

Truncate to current day, at midnight 🧙.

const day = new Date(now.toISOString().slice(0, 10))

Date validation

Given a day in YYYY-MM-DD check if it is valid.

function isValid (day) {
  try {
    var t = new Date(day)
    return t.toISOString().slice(0, 10) === day
  } catch (err) {
    return false
  }
}

isValid('2018-07-16') // true
isValid('2018-02-30') // false
isValid('2018-01-0x') // false