Quiero convertir las horas UTC a la hora local usando JavaScript, ¿es posible?
Tengo las últimas 24 horas en matriz
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"]Leí esta pregunta Convertir hora UTC a local usando moment.js
¿Es posible usar JavaScript simple?
Intenté arreglarlo, pero funciona solo en el horario de India. ¿Qué hacer por otros países?
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');¡Usando new Date().getTimezoneOffset() puede obtener una offset y luego convertirla en hora!
¡Prueba este código que te ayudará!
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');Simplemente puede usar toLocaleTimeString para obtener la hora local
supongamos que su horario UTC es 17
let UTCTime=17:00; var LocalTime=new Date('2021-09-23T'+ UTCTime+ "z").toLocaleTimeString()