DateTime Manipulation in JavaScript

Yehong Piao
2 min readSep 4, 2020

--

  • What is UTC?

Coordinated Universal Time (or UTC) is the primary time standard by which the world regulates clocks and time. It is within about 1 second of mean solar time at 0° longitude, and is not adjusted for daylight saving time. It is effectively a successor to Greenwich Mean Time (GMT).-Wikipedia

** UTC time is 5 hours ahead of Houston local time which is Central Time Zone. **

  • Why we need to save UTC time to database?

Imagine that you made an app, and stored in database using local time. It will be a disaster when it is the time to export the time. Every user who access to your app, will need to do the math and convert the app’s local time to their’s local time.

UTC (Coordinated Universal Time) as its name, it’s a standard and understandable anywhere in the world. So it will be a good reference to set it as a benchmark format for easy conversion.

  • How to change local time to UTC and change it back?

With one of the most useful JavaScript library: moment.js, you can convert time easily along with all other useful format.

const moment = require('moment')** Prints out UTC time **
const utc = moment.utc()
console.log(utc.format('YYYY-MM-DD HH:mm:ss'))
=> 2020-09-04 03:33:11

** Convert to local time **
const local = utc.local()
console.log(local.format('YYYY-MM-DD HH:mm:ss'))
=> 2020-09-03 22:33:11

**Easily add/subtract times**
const localPlusOneHour = local.add(1, 'hour')
console.log(localPlusOneHour.format('YYYY-MM-DD HH:mm:ss'))
=> 2020-09-03 23:33:11
**Easily convert military time to standard time format**
localPlusOneHour.format('YYYY-MM-DD hh:mm:ss a'))
console.log(localPlusOneHour)
=> 2020-09-03 11:33:11 pm

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response