Estoy ubicado en la zona horaria PDT. Cuando escribo new Date() en la consola del navegador, aparece Tue Aug 31 2021 09:43:15 GMT-0700 (Pacific Daylight Time) .
Ahora, quiero la fecha en el mismo formato de la región horaria central.
Así que quiero que el objeto de tiempo se vea así: Aug 31 2021 11:43:15 GMT-0500 (Central Daylight Time)
He estado leyendo los documentos sobre Intl, Intl.DateTimeFormat() y toLocalTimeString() pero parece que no puedo encontrarlo.
new Date().toLocaleString(undefined, { timeZone: "US/Central" }) que me da "31/8/2021, 11:46:30 AM", que es correcto pero no el formato correcto.
Probé el nuevo Intl.DateTimeFormat('en-US', { dateStyle: 'full', timeStyle: 'long', timeZone:"US/Central" }).format(new Date()) que también me da una cadena y no es un objeto de fecha en formato UTC.
¿Qué estoy haciendo mal?
La fecha en JS es un tema complicado. Estoy 100% de acuerdo contigo:
Lo hice una vez de la manera difícil:
Tal vez no sea la forma más elegante, pero funcionó. Cualquier sugerencia de otros colaboradores es muy bienvenida.
Editar:
Se agregó let oTZPartsReduced = ... en respuesta al valioso comentario de @RobG
let myTimeZone = new Date(); console.log(myTimeZone); //console.log((myTimeZone.getTimezoneOffset()/60).toFixed(2)); // oTZ = otherTimeZone (to keep it short) let oTZ = new Date(myTimeZone).toLocaleString("en-US", {timeZone: "US/Central"}); let oTZFormatted; let oTZParts = new Intl.DateTimeFormat('en', { weekday: 'short', day:'2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit', timeZone: 'US/Central' // <-- here it goes, your wished timeZone }).formatToParts(new Date(myTimeZone)); oTZFormatted = oTZParts[2].value + ' ' + oTZParts[4].value + ' '+ oTZParts[6].value + ' '+ oTZParts[8].value + ':'+ oTZParts[10].value + ':'+ oTZParts[12].value + ' GMT-0500 (Central Daylight Time)'; // order within above array could vary due to language as @RobG stated - thanks // hence following reduced version of above array: let oTZPartsReduced = oTZParts.reduce((acc, part) => { if (part.type != 'literal') { acc[part.type] = part.value; } return acc; }, Object.create(null)); oTZFormatted = oTZPartsReduced.month + ' ' + oTZPartsReduced.day + ' '+ oTZPartsReduced.year + ' '+ oTZPartsReduced.hour + ':'+ oTZPartsReduced.minute + ':'+ oTZPartsReduced.second + ' GMT-0500 (Central Daylight Time)'; console.log(oTZFormatted); console.log('Array of Parts for reference:'); console.log(oTZParts); console.log('Object (reduced) of Parts for reference:'); console.log(oTZPartsReduced);