Join 25,000+ Laravel Developers and join the free Laravel Newsletter
Spacetime JavaScript Timezone Library
News / November 06, 2018

Spacetime JavaScript Timezone Library

Now that daylight savings time is over and most states in the US set their clocks back an hour, it reminds me of how difficult dealing with dates can be. For me, being in Arizona means that my time doesn’t change, but I must work with other time zones to figure out how far ahead (or behind) I am with the changes.

Moment.js is excellent for working with dates on the frontend, but I am always on the lookout for lightweight alternatives that include timezone support.

Enter Spacetime.

Spacetime is a lightweight JavaScript timezone library with a Moment.js-like API was written by Spencer Kelly:

<script src=""></script>
  var d = spacetime('March 1 2012', 'America/New_York')
  //set the time


As an NPM dependency npm install spacetime:

const spacetime = require('spacetime')
let d ='Europe/Paris')

Spacetime has zero dependencies and weighs about 45KB at the time of writing. It supports the familiar Moment.js API, which you can see in full in the documentation.

Spacetime supports immutability:

const ImmutableSpacetime = require('spacetime/immutable')
const day0 = new ImmutableSpacetime([2018, 0, 1])

day0.format('nice') // January 1st
day0.add(3, 'days').format('nice') // January 4th
day0.format('nice') // January 1st!

When using ImmutableSpacetime a new instance of Spacetime is always returned, leaving the original date untouched.

One of my favorite features of this library is the goto() method:

let d = spacetime([2018, 11, 5])
// Go to the America/New_York timezone at the same moment

Another cool-looking API is the whereIts() method, which returns all the timezones where it’s within one/many time range(s):

// List of timezones between 8:30am and 10:30am
spacetime.whereIts('8:30am', '10:30am')

// List of timezones within this hour

You can learn more about the full API by visiting the documentation and the source code is available on GitHub.

This appeared first on Laravel News
Laravel News Partners


Join the weekly newsletter and never miss out on new tips, tutorials, and more.