Skip to content

Convert local time to UTC time and vice versa

License

Notifications You must be signed in to change notification settings

geminixandroid/time-converting

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 

Repository files navigation

time-converting

Typescript functions to convert local time to UTC and vise versa using date-fns

import { format, parse } from 'date-fns'

const TIME_FORMAT = 'HH:mm:ss'

function utcToLocalTime(utcTime: string): string {
  const date = parse(utcTime, TIME_FORMAT, new Date())

  return format(
    new Date(
      Date.UTC(
        date.getFullYear(),
        date.getMonth(),
        date.getDate(),
        date.getHours(),
        date.getMinutes(),
        date.getSeconds(),
        date.getMilliseconds()
      )
    ),
    TIME_FORMAT
  )
}

function localTimeToUtc(localTime: string): string {
  const date = parse(localTime, TIME_FORMAT, new Date())

  return format(
    new Date(
      date.getUTCFullYear(),
      date.getUTCMonth(),
      date.getUTCDate(),
      date.getUTCHours(),
      date.getUTCMinutes(),
      date.getUTCSeconds(),
      date.getUTCMilliseconds()
    ),
    TIME_FORMAT
  )
}

About

Convert local time to UTC time and vice versa

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published