Skip to content

Instantly share code, notes, and snippets.

@jonmitten
Last active March 6, 2018 19:12
Show Gist options
  • Save jonmitten/bd2bd0e2ff3634ec77c9bdce99b83a7b to your computer and use it in GitHub Desktop.
Save jonmitten/bd2bd0e2ff3634ec77c9bdce99b83a7b to your computer and use it in GitHub Desktop.
Javascript time conversion and maths

Overview

This Gist aims to serve as a reminder for myself and for anybody who finds this useful. Documenting the various ways of converting time in javascript, making time and date stamps, adding and subtracting time into human-readable formats, the goal is to have snippets and references that are outside of the Mozilla docs, largely drawn from StackOverflow. Links will be provided as available.

Assumptions

It is advisable to keep times in UTC timezone, adjusting to timezones only after all other conversions have taken place. This document assumes UTC as the timezone.

Timestamps

Get the current timestamp with Date.now():

var current_time = Date.now();

> 1520362586914

Result is milliseconds since the Unix epoch of Jan 1, 1970 00:00:00 UTC

Convert timestamp to ISO 8601

Use the Javascript built-in method .toISOString() to convert to the ISO format

var current_iso_time = new Date(current_time).toISOString();

> "2018-03-06T18:56:26.914Z"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment