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 support.

Enter Spacetime.

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

<script src="https://unpkg.com/spacetime"></script>
<script>
  var d = spacetime('March 1 2012', 'America/New_York')
  //set the time
  d.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 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
d.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:30am
spacetime.whereIts('8:30am', '10:30am')

// List of timezones within this hour
spacetime.whereIts('9am')

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



Source link https://-.com/spacetime-js

LEAVE A REPLY

Please enter your comment!
Please enter your name here