Home > Enterprise >  How to convert UTC hours to local using Javascript
How to convert UTC hours to local using Javascript

Time:01-10

I want to convert UTC hours to local time using JavaScript it is possible ?

I have last 24 hours in array

let _arrHours = ["4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","1","2","3"]

I read this question Convert Hour UTC to Local using moment.js

It's possible using simple JavaScript ?

I have try to fix it but it's works only India time ? what do for other countries ?

  let _arrHours = ["4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "1", "2", "3"];
    let _arrDt = [];
    for (let t = 0; t < _arrHours.length; t  ) {
      let tm = _arrHours[t];
      tm = parseInt(tm)   5.5; //indian timezone, I want to do it dynamic country wise !
      if (tm > 24) {
        tm = tm - 24;
      }
      else if (tm < 0) {
        tm = tm   24;
      }
      _arrDt.push(tm);
    }

    console.log(_arrDt, '_arrDt'); 

CodePudding user response:

Using new Date().getTimezoneOffset() you can get offset then convert into hour !

Try this code it's help you !

 let offset = new Date().getTimezoneOffset(); //get the country wise offset !
    if (offset > 0) { //let's convert in to hour
      offset = (-Math.abs(offset / 60));
    } else {
      offset = (Math.abs(offset / 60));
    }
    let _arrHours = ["4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "1", "2", "3"];
    let _arrDt = [];
    for (let t = 0; t < _arrHours.length; t  ) {
      let tm = _arrHours[t];
      tm = parseInt(tm)   offset;
      if (tm > 24) {
        tm = tm - 24;
      }
      else if (tm < 0) {
        tm = tm   24;
      }
      _arrDt.push(tm);
    }

    console.log(_arrDt, '_arrDt');

CodePudding user response:

You can simply use toLocaleTimeString to get local time

let assume you UTC hours is 17

let UTCTime=17:00;

var LocalTime=new Date('2021-09-23T'  UTCTime  "z").toLocaleTimeString()
  •  Tags:  
  • Related