Konwertuj czas UTC na czas lokalny
Z serwera dostaję zmienną datetime w tym formacie: 6/29/2011 4:52:48 PM
i jest ona w czasie UTC. Chcę przekonwertować go na czas przeglądarki bieżącego użytkownika za pomocą JavaScript.
Jak można to zrobić za pomocą JavaScript lub jQuery?
23 answers
Dołączenie " UTC " do łańcucha przed konwersją go na datę w javascript:
var date = new Date('6/29/2011 4:52:48 PM UTC');
date.toString() // "Wed Jun 29 2011 09:52:48 GMT-0700 (PDT)"
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-06-29 18:42:22
Jest to rozwiązanie uniwersalne:
function convertUTCDateToLocalDate(date) {
var newDate = new Date(date.getTime()+date.getTimezoneOffset()*60*1000);
var offset = date.getTimezoneOffset() / 60;
var hours = date.getHours();
newDate.setHours(hours - offset);
return newDate;
}
Użycie:
var date = convertUTCDateToLocalDate(new Date(date_string_you_received));
Wyświetl datę na podstawie lokalnego ustawienia klienta:
date.toLocaleString();
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-11 20:18:40
Z mojego punktu widzenia serwery powinny zawsze w ogólnym przypadku zwracać datetime w standardzie ISO 8601-format .
Więcej informacji tutaj:
W tym przypadku serwer zwróci '2011-06-29T16:52:48.000Z'
, który będzie zasilany bezpośrednio do obiektu JS Date.
var utcDate = '2011-06-29T16:52:48.000Z'; // ISO-8601 formatted date returned from server
var localDate = new Date(utcDate);
localDate
będzie we właściwym czasie lokalnym, który w moim przypadku będzie wynosił dwie godziny później (czas DK).
Ty naprawdę nie musisz robić tego całego parsowania, które tylko komplikuje sprawy, o ile jesteś zgodny z formatem, którego oczekujesz od serwera.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-13 18:52:18
Powinieneś otrzymać offset (UTC) (w minutach) klienta:
var offset = new Date().getTimezoneOffset();
A następnie wykonaj dodawanie lub odejmowanie do czasu, który uzyskasz z serwera.
Mam nadzieję, że to pomoże.Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-06-29 18:46:16
Umieść tę funkcję w głowie:
<script type="text/javascript">
function localize(t)
{
var d=new Date(t+" UTC");
document.write(d.toString());
}
</script>
Następnie Wygeneruj dla każdej daty w treści strony:
<script type="text/javascript">localize("6/29/2011 4:52:48 PM");</script>
Aby usunąć GMT i strefę czasową, Zmień następującą linię:
document.write(d.toString().replace(/GMT.*/g,""));
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-02-16 19:26:41
Użyj tego do konwersji czasu UTC i Lokalnego i odwrotnie.
//Covert datetime by GMT offset
//If toUTC is true then return UTC time other wise return local time
function convertLocalDateToUTCDate(date, toUTC) {
date = new Date(date);
//Local time converted to UTC
console.log("Time: " + date);
var localOffset = date.getTimezoneOffset() * 60000;
var localTime = date.getTime();
if (toUTC) {
date = localTime + localOffset;
} else {
date = localTime - localOffset;
}
date = new Date(date);
console.log("Converted time: " + date);
return date;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-30 18:03:38
Po wypróbowaniu kilku innych zamieszczonych tutaj bez dobrych rezultatów, wydawało mi się, że działa:
convertUTCDateToLocalDate: function (date) {
return new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()));
}
I działa to w odwrotną stronę, od lokalnej daty Do UTC:
convertLocalDatetoUTCDate: function(date){
return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-10 19:30:50
Dla mnie powyższe rozwiązania nie zadziałały.
W IE konwersja czasu UTC na lokalny jest trochę trudna.
Dla mnie data-czas z web API to '2018-02-15T05:37:26.007'
i chciałem przekonwertować zgodnie z lokalną strefą czasową, więc użyłem poniższego kodu w JavaScript.
var createdDateTime = new Date('2018-02-15T05:37:26.007' + 'Z');
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-16 09:33:24
W odpowiedzi Matta brakuje faktu, że czas letni może być różny między Date () a datą, która musi zostać przekonwertowana - oto moje rozwiązanie:
function ConvertUTCTimeToLocalTime(UTCDateString)
{
var convertdLocalTime = new Date(UTCDateString);
var hourOffset = convertdLocalTime.getTimezoneOffset() / 60;
convertdLocalTime.setHours( convertdLocalTime.getHours() + hourOffset );
return convertdLocalTime;
}
I wyniki w debuggerze:
UTCDateString: "2014-02-26T00:00:00"
convertdLocalTime: Wed Feb 26 2014 00:00:00 GMT-0800 (Pacific Standard Time)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-04 01:18:10
W przypadku, gdy nie masz nic przeciwko użyciumoment.js
i twój czas jest w UTC wystarczy użyć następujących:
moment.utc('6/29/2011 4:52:48 PM').toDate();
Jeśli twój czas nie jest w utc, ale w innych znanych ci lokalizacjach, użyj następującego:
moment('6/29/2011 4:52:48 PM', 'MM-DD-YYYY', 'fr').toDate();
Jeśli twój czas jest już lokalny, użyj następującego:
moment('6/29/2011 4:52:48 PM', 'MM-DD-YYYY');
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-29 05:23:40
Jest to uproszczone rozwiązanie oparte na Adorjan Princs odpowiedź:
function convertUTCDateToLocalDate(date) {
var newDate = new Date(date);
newDate.setMinutes(date.getMinutes() - date.getTimezoneOffset());
return newDate;
}
Użycie:
var date = convertUTCDateToLocalDate(new Date(date_string_you_received));
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-03 09:45:41
To działa dla mnie:
function convertUTCDateToLocalDate(date) {
var newDate = new Date(date.getTime() - date.getTimezoneOffset()*60*1000);
return newDate;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-22 18:13:14
Dla mnie najprostszy wydawał się
datetime.setUTCHours(datetime.getHours());
datetime.setUTCMinutes(datetime.getMinutes());
(myślałem, że pierwsza linia może wystarczyć, ale są strefy czasowe, które są wyłączone w ułamkach godzin)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-06-14 09:40:59
Użycie formatu YYYY-MM-DD hh:mm:ss
:
var date = new Date('2011-06-29T16:52:48+00:00');
date.toString() // "Wed Jun 29 2011 09:52:48 GMT-0700 (PDT)"
Aby konwertować z formatu YYYY-MM-DD hh:mm:ss
, Upewnij się, że data jest zgodna z ISO 8601 Format .
Year:
YYYY (eg 1997)
Year and month:
YYYY-MM (eg 1997-07)
Complete date:
YYYY-MM-DD (eg 1997-07-16)
Complete date plus hours and minutes:
YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00)
Complete date plus hours, minutes and seconds:
YYYY-MM-DDThh:mm:ssTZD (eg 1997-07-16T19:20:30+01:00)
Complete date plus hours, minutes, seconds and a decimal fraction of a second
YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00) where:
YYYY = four-digit year
MM = two-digit month (01=January, etc.)
DD = two-digit day of month (01 through 31)
hh = two digits of hour (00 through 23) (am/pm NOT allowed)
mm = two digits of minute (00 through 59)
ss = two digits of second (00 through 59)
s = one or more digits representing a decimal fraction of a second
TZD = time zone designator (Z or +hh:mm or -hh:mm)
Ważne rzeczy do odnotowania
- musisz oddzielić datę i godzinę przez
T
, spacja nie będzie działać w niektórych przeglądarkach - musisz ustawić strefę czasową używając tego formatu
+hh:mm
, używając ciągu znaków dla strefy czasowej (np. : 'UTC') nie będzie działać w wielu przeglądarkach.+hh:mm
reprezentują offset z UTC Strefa czasowa.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-25 12:57:51
Łańcuch daty JSON (serializowany w C#) wygląda jak "2015-10-13t18:58:17".
W angular, (po Hulvej) make a localdate
filter:
myFilters.filter('localdate', function () {
return function(input) {
var date = new Date(input + '.000Z');
return date;
};
})
Następnie Wyświetl czas lokalny w następujący sposób:
{{order.createDate | localdate | date : 'MMM d, y h:mm a' }}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-13 19:44:03
Dodaj strefę czasową na końcu, w tym przypadku 'UTC':
theDate = new Date( Date.parse('6/29/2011 4:52:48 PM UTC'));
Następnie użyj tolokale()* rodziny funkcji do wyświetlania daty w poprawnym locale
theDate.toLocaleString(); // "6/29/2011, 9:52:48 AM"
theDate.toLocaleTimeString(); // "9:52:48 AM"
theDate.toLocaleDateString(); // "6/29/2011"
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-09 23:19:24
Odpowiadam na to, jeśli któraś z nich chce funkcji, która wyświetla konwertowany czas na określony element id i stosuje format daty string yyyy-mm-dd tutaj date1 to string, a ids to id elementu, który ma zostać wyświetlony.
function convertUTCDateToLocalDate(date1, ids)
{
var newDate = new Date();
var ary = date1.split(" ");
var ary2 = ary[0].split("-");
var ary1 = ary[1].split(":");
var month_short = Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
newDate.setUTCHours(parseInt(ary1[0]));
newDate.setUTCMinutes(ary1[1]);
newDate.setUTCSeconds(ary1[2]);
newDate.setUTCFullYear(ary2[0]);
newDate.setUTCMonth(ary2[1]);
newDate.setUTCDate(ary2[2]);
ids = document.getElementById(ids);
ids.innerHTML = " " + newDate.getDate() + "-" + month_short[newDate.getMonth() - 1] + "-" + newDate.getFullYear() + " " + newDate.getHours() + ":" + newDate.getMinutes() + ":" + newDate.getSeconds();
}
Wiem, że odpowiedź została już zaakceptowana, ale trafiłem tutaj z powodu google i rozwiązałem z czerpaniem inspiracji z zaakceptowanej odpowiedzi, więc chciałem się nią podzielić, jeśli ktoś będzie potrzebował.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-28 14:09:07
Na podstawie odpowiedzi @digitalbath, oto mała funkcja do przechwytywania znacznika czasu UTC i wyświetlania czasu lokalnego w danym elemencie DOM (używając jQuery do tej ostatniej części):
Https://jsfiddle.net/moriz/6ktb4sv8/1/
<div id="eventTimestamp" class="timeStamp">
</div>
<script type="text/javascript">
// Convert UTC timestamp to local time and display in specified DOM element
function convertAndDisplayUTCtime(date,hour,minutes,elementID) {
var eventDate = new Date(''+date+' '+hour+':'+minutes+':00 UTC');
eventDate.toString();
$('#'+elementID).html(eventDate);
}
convertAndDisplayUTCtime('06/03/2015',16,32,'eventTimestamp');
</script>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-01 00:21:18
@Adorojan's
Odpowiedź jest prawie poprawna. Ale dodanie offsetu nie jest poprawne, ponieważ wartość offsetu będzie ujemna, jeśli data przeglądarki jest przed GMT i odwrotnie.
Poniżej znajduje się rozwiązanie, z którym przyszedłem i działa dla mnie doskonale: {]}
// Input time in UTC
var inputInUtc = "6/29/2011 4:52:48";
var dateInUtc = new Date(Date.parse(inputInUtc+" UTC"));
//Print date in UTC time
document.write("Date in UTC : " + dateInUtc.toISOString()+"<br>");
var dateInLocalTz = convertUtcToLocalTz(dateInUtc);
//Print date in local time
document.write("Date in Local : " + dateInLocalTz.toISOString());
function convertUtcToLocalTz(dateInUtc) {
//Convert to local timezone
return new Date(dateInUtc.getTime() - dateInUtc.getTimezoneOffset()*60*1000);
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-19 20:31:43
Możesz użyć momentjs ,moment(date).format()
zawsze da wynik w Data lokalna.
Bonus , możesz formatować w dowolny sposób. Dla np.
moment().format('MMMM Do YYYY, h:mm:ss a'); // September 14th 2018, 12:51:03 pm
moment().format('dddd'); // Friday
moment().format("MMM Do YY");
Po Więcej Szczegółów możesz zapoznać się z Moment js website
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-14 07:24:55
Napisałem ładny skrypt, który zajmuje czas UTC i konwertuje go do strefy czasowej systemu klienta i zwraca go w formacie d/m / Y H:I:s (jak funkcja PHP date):
getTimezoneDate = function ( e ) {
function p(s) { return (s < 10) ? '0' + s : s; }
var t = new Date(0);
t.setUTCSeconds(e);
var d = p(t.getDate()),
m = p(t.getMonth()+1),
Y = p(t.getFullYear()),
H = p(t.getHours()),
i = p(t.getMinutes()),
s = p(t.getSeconds());
d = [d, m, Y].join('/') + ' ' + [H, i, s].join(':');
return d;
};
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-24 14:26:48
function getUTC(str) {
var arr = str.split(/[- :]/);
var utc = new Date(arr[0], arr[1]-1, arr[2], arr[3], arr[4], arr[5]);
utc.setTime(utc.getTime() - utc.getTimezoneOffset()*60*1000)
return utc;
}
Dla innych, którzy odwiedzają-użyj tej funkcji, aby uzyskać lokalny obiekt daty Z ciągu UTC, powinien zająć się DST i będzie działać na IE, IPhone itp.
Dzielimy łańcuch (ponieważ parsowanie dat JS nie jest obsługiwane w niektórych przeglądarkach) Otrzymujemy różnicę od czasu UTC i odejmujemy ją od czasu UTC, co daje nam czas lokalny. Ponieważ offset zwrócony jest obliczany z DST (popraw mnie, jeśli się mylę), więc ustawi ten czas z powrotem w zmiennej "utc". Na koniec zwróć datę obiekt.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-29 18:14:03
W Angular użyłem odpowiedzi Bena w ten sposób:
$scope.convert = function (thedate) {
var tempstr = thedate.toString();
var newstr = tempstr.toString().replace(/GMT.*/g, "");
newstr = newstr + " UTC";
return new Date(newstr);
};
Edit: Angular 1.3.0 dodano obsługę UTC do filtra daty, jeszcze go nie używałem, ale powinno być łatwiej, oto format:
{{ date_expression | date : format : timezone}}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-29 17:30:40