variable obtener manejo hora fechas fecha actual javascript date utc epoch

javascript - obtener - typescript fecha actual



Convertir UTC Época a fecha local (12)

He estado luchando con esto por un poco ahora. Estoy tratando de convertir la época en un objeto de fecha. La época me es enviada en UTC. Cada vez que se pasa una new Date() una época, se asume que es una época local. Intenté crear un objeto UTC, luego usar setTime() para ajustarlo a la época apropiada, pero el único método que parece útil es toUTCString() y las cadenas no me ayudan. Si paso esa cadena a una nueva fecha, debería notar que es UTC, pero no lo hace.

new Date( new Date().toUTCString() ).toLocaleString()

Mi siguiente intento fue tratar de obtener la diferencia entre la época actual local y la actual UTC, pero tampoco pude conseguir eso.

new Date( new Date().toUTCString() ).getTime() - new Date().getTime()

Solo me está dando diferencias muy pequeñas, por debajo de 1000, que es en milisegundos.

¿Alguna sugerencia?


¿Está pidiendo convertir una cadena UTC en una cadena "local"? Podrías hacerlo:

var utc_string = ''2011-09-05 20:05:15''; var local_string = (function(dtstr) { var t0 = new Date(dtstr); var t1 = Date.parse(t0.toUTCString().replace(''GMT'', '''')); var t2 = (2 * t0) - t1; return new Date(t2).toString(); })(utc_string);


@Amjad, buena idea, pero mal implementado. Tratar

Date.prototype.setUTCTime = function(UTCTimestamp) { var UTCDate = new Date(UTCTimestamp); this.setUTCFullYear(UTCDate.getFullYear(), UTCDate.getMonth(), UTCDate.getDate()); this.setUTCHours(UTCDate.getHours(), UTCDate.getMinutes(), UTCDate.getSeconds(), UTCDate.getMilliseconds()); return this.getTime(); }


Creo que tengo una solución más simple: establezca la fecha inicial en la época y agregue unidades UTC. Digamos que usted tiene una época UTC var almacenada en segundos. ¿Qué tal 1234567890 . Para convertir eso en una fecha adecuada en la zona horaria local:

var utcSeconds = 1234567890; var d = new Date(0); // The 0 there is the key, which sets the date to the epoch d.setUTCSeconds(utcSeconds);

d es ahora una fecha (en mi zona horaria) configurada para Fri Feb 13 2009 18:31:30 GMT-0500 (EST)


El tiempo de la época es en segundos desde el 1 de enero de 1970. date.getTime() devuelve milisegundos desde el 1 de enero de 1970, así que ... si tiene una marca de tiempo de la época, conviértalo en una marca de tiempo de javascript multiplicando por 1000.

function epochToJsDate(ts){ // ts = epoch timestamp // returns date obj return new Date(ts*1000); } function jsDateToEpoch(d){ // d = javascript date obj // returns epoch timestamp return (d.getTime()-d.getMilliseconds())/1000; }


Es fácil, la new Date() solo toma milisegundos, por ejemplo

new Date(1394104654000) > Thu Mar 06 2014 06:17:34 GMT-0500 (EST)


Para convertir el tiempo de época actual en [ms] a un tiempo de 24 horas. Es posible que deba especificar la opción para deshabilitar el formato de 12 horas .

$ node.exe -e "var date = new Date(Date.now()); console.log(date.toLocaleString(''en-GB'', { hour12:false } ));" 2/7/2018, 19:35:24

o como JS:

var date = new Date(Date.now()); console.log(date.toLocaleString(''en-GB'', { hour12:false } )); // 2/7/2018, 19:35:24 console.log(date.toLocaleString(''en-GB'', { hour:''numeric'', minute:''numeric'', second:''numeric'', hour12:false } )); // 19:35:24

Nota: el uso de en-GB aquí, es solo una elección (aleatoria) de un lugar utilizando el formato de 24 horas, ¡no es su zona horaria!


Primero conviértalo a String y luego reemplace el texto de la zona horaria.

function convertUnixTime(time) { return new Date(time*1000).toString().replace("GMT+0530 (Sri Lanka Standard Time)",""); }


Si prefiere resolver las conversiones de fecha y hora y de UTC y hora local sin bibliotecas como moment.js, consulte la siguiente opción.

Para aplicaciones que usan marcas de tiempo UTC, es posible que deba mostrar la fecha en el navegador considerando la zona horaria local y el horario de verano cuando corresponda. Editar una fecha que se encuentra en un horario de verano diferente, aunque en la misma zona horaria puede ser complicado.

Las extensiones de Number y Date continuación le permiten mostrar y obtener fechas en la zona horaria de las marcas de tiempo. Por ejemplo, digamos que está en Vancouver, si está editando una fecha en julio o en diciembre, puede significar que está editando una fecha en PST o PDT.

Le recomiendo que consulte el Fragmento de código a continuación para probar esta solución.

Conversiones de milisegundos

Number.prototype.toLocalDate = function () { var value = new Date(this); value.setHours(value.getHours() + (value.getTimezoneOffset() / 60)); return value; }; Number.prototype.toUTCDate = function () { var value = new Date(this); value.setHours(value.getHours() - (value.getTimezoneOffset() / 60)); return value; };

Conversiones de fechas

Date.prototype.getUTCTime = function () { return this.getTime() - (this.getTimezoneOffset() * 60000); };

Uso

// Adds the timezone and daylight savings if applicable (1499670000000).toLocalDate(); // Eliminates the timezone and daylight savings if applicable new Date(2017, 6, 10).getUTCTime();

Verlo por ti mismo

// Extending Number Number.prototype.toLocalDate = function () { var value = new Date(this); value.setHours(value.getHours() + (value.getTimezoneOffset() / 60)); return value; }; Number.prototype.toUTCDate = function () { var value = new Date(this); value.setHours(value.getHours() - (value.getTimezoneOffset() / 60)); return value; }; // Extending Date Date.prototype.getUTCTime = function () { return this.getTime() - (this.getTimezoneOffset() * 60000); }; // Getting the demo to work document.getElementById(''m-to-local-button'').addEventListener(''click'', function () { var displayElement = document.getElementById(''m-to-local-display''), value = document.getElementById(''m-to-local'').value, milliseconds = parseInt(value); if (typeof milliseconds === ''number'') displayElement.innerText = (milliseconds).toLocalDate().toISOString(); else displayElement.innerText = ''Set a value''; }, false); document.getElementById(''m-to-utc-button'').addEventListener(''click'', function () { var displayElement = document.getElementById(''m-to-utc-display''), value = document.getElementById(''m-to-utc'').value, milliseconds = parseInt(value); if (typeof milliseconds === ''number'') displayElement.innerText = (milliseconds).toUTCDate().toISOString(); else displayElement.innerText = ''Set a value''; }, false); document.getElementById(''date-to-utc-button'').addEventListener(''click'', function () { var displayElement = document.getElementById(''date-to-utc-display''), yearValue = document.getElementById(''date-to-utc-year'').value || ''1970'', monthValue = document.getElementById(''date-to-utc-month'').value || ''0'', dayValue = document.getElementById(''date-to-utc-day'').value || ''1'', hourValue = document.getElementById(''date-to-utc-hour'').value || ''0'', minuteValue = document.getElementById(''date-to-utc-minute'').value || ''0'', secondValue = document.getElementById(''date-to-utc-second'').value || ''0'', year = parseInt(yearValue), month = parseInt(monthValue), day = parseInt(dayValue), hour = parseInt(hourValue), minute = parseInt(minuteValue), second = parseInt(secondValue); displayElement.innerText = new Date(year, month, day, hour, minute, second).getUTCTime(); }, false);

<link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.11/semantic.css" rel="stylesheet"/> <div class="ui container"> <p></p> <h3>Milliseconds to local date</h3> <input id="m-to-local" placeholder="Timestamp" value="0" /> <button id="m-to-local-button">Convert</button> <em id="m-to-local-display">Set a value</em> <h3>Milliseconds to UTC date</h3> <input id="m-to-utc" placeholder="Timestamp" value="0" /> <button id="m-to-utc-button">Convert</button> <em id="m-to-utc-display">Set a value</em> <h3>Date to milliseconds in UTC</h3> <input id="date-to-utc-year" placeholder="Year" style="width: 4em;" /> <input id="date-to-utc-month" placeholder="Month" style="width: 4em;" /> <input id="date-to-utc-day" placeholder="Day" style="width: 4em;" /> <input id="date-to-utc-hour" placeholder="Hour" style="width: 4em;" /> <input id="date-to-utc-minute" placeholder="Minute" style="width: 4em;" /> <input id="date-to-utc-second" placeholder="Second" style="width: 4em;" /> <button id="date-to-utc-button">Convert</button> <em id="date-to-utc-display">Set the values</em> </div>


Teniendo en cuenta, tienes epoch_time disponible,

// for eg. epoch_time = 1487086694.213 var date = new Date(epoch_time * 1000); // multiply by 1000 for milliseconds var date_string = date.toLocaleString(''en-GB''); // 24 hour format


Y solo para los registros, lo hice utilizando la biblioteca Moment.js , que estaba usando para el formateo de todos modos.

moment.utc(1234567890000).local() >Fri Feb 13 2009 19:01:30 GMT-0430 (VET)


EDITAR

var utcDate = new Date(incomingUTCepoch); var date = new Date(); date.setUTCDate(utcDate.getDate()); date.setUTCHours(utcDate.getHours()); date.setUTCMonth(utcDate.getMonth()); date.setUTCMinutes(utcDate.getMinutes()); date.setUTCSeconds(utcDate.getSeconds()); date.setUTCMilliseconds(utcDate.getMilliseconds());

EDITAR fijo


function ToLocalDate (inDate) { var date = new Date(); date.setTime(inDate.valueOf() - 60000 * inDate.getTimezoneOffset()); return date; }