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.
<script src="https://unpkg.com/spacetime"></script><script>var d = spacetime('March 1 2012', 'America/New_York')//set the timed.time('4:20pm')d.goto('America/Los_Angeles')d.time()//'1:20pm'</script>
As an NPM dependency
npm install spacetime:
const spacetime = require('spacetime')let d = spacetime.now('Europe/Paris')d.dayName()//'Wednesday'd.isAsleep()//true
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 1stday0.add(3, 'days').format('nice') // January 4thday0.format('nice') // January 1st!
ImmutableSpacetime a new instance of Spacetime is always returned, leaving the original date untouched.
One of my favorite features of this library is the
let d = spacetime([2018, 11, 5])// Go to the America/New_York timezone at the same momentd.goto('America/New_York');
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:30amspacetime.whereIts('8:30am', '10:30am')// List of timezones within this hourspacetime.whereIts('9am')
You can learn more about the full API by visiting the documentation and the source code is available on GitHub.
Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.