Konwertuj datę na inną strefę czasową w JavaScript

Szukam funkcji do konwersji daty w jednej strefie czasowej na inną.

Potrzebne są dwa parametry,

  • Data (w formacie "2012/04/10 10:10:30 +0000")
  • timezone string ("Azja/Dżakarta")

Łańcuch strefy czasowej jest opisany w http://en.wikipedia.org/wiki/Zone.tab

Czy jest na to łatwy sposób?

Author: AstroCB, 2012-04-10

18 answers

Na chwilę.użytkownicy js, możesz teraz używać moment-timezone. Używając go, twoja funkcja wyglądałaby mniej więcej tak: {]}

function toTimeZone(time, zone) {
    var format = 'YYYY/MM/DD HH:mm:ss ZZ';
    return moment(time, format).tz(zone).format(format);
}
 117
Author: Brian Di Palma,
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-05-06 19:44:17

Skradzione bezwstydnie z: http://www.techrepublic.com/article/convert-the-local-time-to-another-time-zone-with-this-javascript/6016329{[3]

/** 
 * function to calculate local time
 * in a different city
 * given the city's UTC offset
 */
function calcTime(city, offset) {

    // create Date object for current location
    var d = new Date();

    // convert to msec
    // add local time zone offset
    // get UTC time in msec
    var utc = d.getTime() + (d.getTimezoneOffset() * 60000);

    // create new Date object for different city
    // using supplied offset
    var nd = new Date(utc + (3600000*offset));

    // return time as a string
    return "The local time in " + city + " is " + nd.toLocaleString();
}

Ta funkcja jest przydatna do obliczania wartości strefy czasowej poprzez podanie nazwy miasta / kraju i wartości offsetu

 81
Author: Valli69,
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-04-19 09:54:10

Większość przeglądarek stacjonarnych (nie mobilnych) z wyjątkiem Safari obsługuje funkcję toLocaleString z argumentami, starsze przeglądarki zwykle ignorują argumenty.

new Date().toLocaleString('en-US', { timeZone: 'Asia/Jakarta' })
 74
Author: lambinator,
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-10-16 17:12:56

/ Align = "left" /

Używam timezone-js. jest to kod:

var dt = new timezoneJS.Date("2012/04/10 10:10:30 +0000", 'Europe/London');
dt.setTimezone("Asia/Jakarta");

console.debug(dt); //return formatted date-time in asia/jakarta
 62
Author: Rizky Ramadhan,
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-04-16 06:14:19

Mam !

Chciał wymusić datę pokazaną = Data serwera, nie zmieniając ustawień lokalnych (UTC).

Mój serwer to GMT-6 -- > new Date().getTimezoneOffset () = 360.

myTZO = 360;
myNewDate=new Date(myOldDateObj.getTime() + (60000*(myOldDateObj.getTimezoneOffset()-myTZO)));
alert(myNewDate);
 8
Author: Cedric Simon,
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-17 01:19:51

Jeśli potrzebujesz tylko przekonwertować strefy czasowe, załadowałem okrojoną wersję z Strefa czasowa z minimalną funkcjonalnością. Its ~1KB + DANE:

S.loadData({
    "zones": [
        "Europe/Paris|CET CEST|-10 -20|01010101010101010101010|1GNB0 1qM0 11A0 1o00 11A0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0 WM0 1qM0 11A0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0|11e6",
        "Australia/Sydney|AEDT AEST|-b0 -a0|01010101010101010101010|1GQg0 1fA0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1fA0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0|40e5",
    ],
    "links": [
        "Europe/Paris|Europe/Madrid",
    ]
});

let d = new Date();
console.log(S.tz(d, "Europe/Madrid").toLocaleString());
console.log(S.tz(d, "Australia/Sydney").toLocaleString());
 4
Author: Santiago Corredoira,
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-22 16:19:53

Ustaw zmienną z rokiem, miesiącem i dniem oddzielonymi symbolami' -', plus' T ' i czasem we wzorze HH:mm:ss, a następnie +01: 00 na końcu łańcucha (w moim przypadku Strefa czasowa to +1). Następnie użyj tego ciągu jako argumentu konstruktora daty.

//desired format: 2001-02-04T08:16:32+01:00
dateAndTime = year+"-"+month+"-"+day+"T"+hour+":"+minutes+":00+01:00";

var date = new Date(dateAndTime );
 2
Author: Nather Webber,
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-11-03 19:13:29

Możesz użyć metody to toLocaleString() do Ustawienia strefy czasowej.

new Date().toLocaleString('en-US', { timeZone: 'Indian/Christmas' })

Dla Indii możesz użyć "Indian / Christmas" i poniżej znajdują się różne strefy czasowe,

"Antarctica/Davis",
    "Asia/Bangkok",
    "Asia/Hovd",
    "Asia/Jakarta",
    "Asia/Phnom_Penh",
    "Asia/Pontianak",
    "Asia/Saigon",
    "Asia/Vientiane",
    "Etc/GMT-7",
    "Indian/Christmas"
 2
Author: Codemaker,
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-07-10 08:13:17

Możesz spróbować tego również dla konwersji strefy czasowej daty Na Indie:

var indianTimeZoneVal = new Date().toLocaleString('en-US', {timeZone: 'Asia/Kolkata'});
var indainDateObj = new Date(indianTimeZoneVal);
indainDateObj.setHours(indainDateObj.getHours() + 5);
indainDateObj.setMinutes(indainDateObj.getMinutes() + 30);
console.log(indainDateObj);
 1
Author: Rahul Mankar,
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-29 07:15:29

Powinienem zauważyć, że jestem ograniczony w odniesieniu do zewnętrznych bibliotek, z których mogę korzystać. chwila.js i timezone-js nie były dla mnie opcją.

Obiekt daty js, który mam jest w UTC. Musiałem uzyskać datę i godzinę od tej daty w określonej strefie czasowej ('Ameryka / Chicago'w moim przypadku).

 var currentUtcTime = new Date(); // This is in UTC

 // Converts the UTC time to a locale specific format, including adjusting for timezone.
 var currentDateTimeCentralTimeZone = new Date(currentUtcTime.toLocaleString('en-US', { timeZone: 'America/Chicago' }));

 console.log('currentUtcTime: ' + currentUtcTime.toLocaleDateString());
 console.log('currentUtcTime Hour: ' + currentUtcTime.getHours());
 console.log('currentUtcTime Minute: ' + currentUtcTime.getMinutes());
 console.log('currentDateTimeCentralTimeZone: ' +        currentDateTimeCentralTimeZone.toLocaleDateString());
 console.log('currentDateTimeCentralTimeZone Hour: ' + currentDateTimeCentralTimeZone.getHours());
 console.log('currentDateTimeCentralTimeZone Minute: ' + currentDateTimeCentralTimeZone.getMinutes());

UTC jest obecnie o 6 godzin przed "America / Chicago". Wyjście to:

currentUtcTime: 11/25/2016
currentUtcTime Hour: 16
currentUtcTime Minute: 15

currentDateTimeCentralTimeZone: 11/25/2016
currentDateTimeCentralTimeZone Hour: 10
currentDateTimeCentralTimeZone Minute: 15
 1
Author: seeking27,
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-11-25 16:26:21

Osoby zaznajomione z pakietem java 8 java.time lub joda-time prawdopodobnie pokochają nową bibliotekę kid on the block: js-joda.

Install

npm install js-joda js-joda-timezone --save

Przykład

<script src="node_modules/js-joda/dist/js-joda.js"></script>
<script src="node_modules/js-joda-timezone/dist/js-joda-timezone.js"></script>
<script>
var dateStr = '2012/04/10 10:10:30 +0000';
JSJoda.use(JSJodaTimezone);
var j = JSJoda;
// https://js-joda.github.io/js-joda/esdoc/class/src/format/DateTimeFormatter.js~DateTimeFormatter.html#static-method-of-pattern
var zonedDateTime = j.ZonedDateTime.parse(dateStr, j.DateTimeFormatter.ofPattern('yyyy/MM/dd HH:mm:ss xx'));
var adjustedZonedDateTime = zonedDateTime.withZoneSameInstant(j.ZoneId.of('America/New_York'));
console.log(zonedDateTime.toString(), '=>', adjustedZonedDateTime.toString());
// 2012-04-10T10:10:30Z => 2012-04-10T06:10:30-04:00[America/New_York]
</script>

W prawdziwej naturze Javy, to dość gadatliwe lol. Ale, będąc przeportowaną biblioteką Javy, szczególnie biorąc pod uwagę, że przeportowali przypadki testowe 1800 ' ish, prawdopodobnie działa ona doskonale dokładnie.

Manipulacja Chrono jest trudna. Dlatego wiele innych bibliotek jest wadliwych w przypadku krawędzi. Chwila.js wydaje aby uzyskać odpowiednie strefy czasowe, ale inne biblioteki js, które widziałem, w tym timezone-js, nie wydają się godne zaufania.
 1
Author: goat,
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-12-14 00:14:19

Jeśli format nie jest bardzo ważny i nie chcesz importować jakiejś dużej biblioteki, możesz po prostu użyć Intl.DateTimeFormat do konwersji obiektów daty na różne strefy czasowe.

const options = {
  year: '2-digit', month: '2-digit', day: '2-digit',
  hour: '2-digit', minute: '2-digit', second: '2-digit',
  timeZone: 'Asia/Jakarta',
  timeZoneName: 'short'
};

const formater = new Intl.DateTimeFormat('sv-SE', options)
const date = new Date("2012/04/10 10:10:30 +0000")

console.log(formater.format(date))

Przesunięcia, czas letni i inne różnice zmienione w przeszłości zostaną za ciebie załatwione

Możesz eksperymentować z językiem, aby uzyskać inne literały.
 1
Author: Endless,
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-04 10:02:00

Miałem problem z używaniem strefy czasowej Moment . Dodaję tę odpowiedź tylko po to, żeby ktoś inny miał ten sam problem. Więc mam ciąg daty 2018-06-14 13:51:00 pochodzący z mojego API. Wiem, że to jest przechowywane w UTC, ale łańcuch nie mówi sam za siebie.

Pozwalam znać strefę czasową, z której strefy czasowej pochodzi ta data, wykonując:

let uTCDatetime = momentTz.tz("2018-06-14 13:51:00", "UTC").format();
// If your datetime is from any other timezone then add that instead of "UTC"
// this actually makes the date as : 2018-06-14T13:51:00Z

Teraz chciałbym przekonwertować go do określonej strefy czasowej wykonując:

let dateInMyTimeZone = momentTz.tz(uTCDatetime, "Asia/Kolkata").format("YYYY-MM-DD HH:mm:ss");
// now this results into: 2018-06-14 19:21:00, which is the corresponding date in my timezone.
 1
Author: Ashish Ranjan,
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-06 13:54:04

Po obejrzeniu wielu linków z tej strony znalazłem ten świetny artykuł, używając strefy czasowej momentu:

Https://www.webniraj.com/2016/11/23/javascript-using-moment-js-to-display-dates-times-in-users-timezone/

Podsumowując:

Get the user ' s timezone

var tz = moment.tz.guess();
console.info('Timezone: ' + tz);

Zwraca np: Timezone: Europe / London

Ustaw domyślną strefę czasową użytkownika

moment.tz.setDefault(tz);

Ustaw własną strefę czasową

moment.tz.setDefault('America/Los_Angeles');

Konwertuj datę / czas na lokalną strefę czasową, zakłada, że oryginalna Data / Czas jest w UTC

moment.utc('2016-12-25 07:00').tz(tz).format('ddd, Do MMMM YYYY, h:mma');

Powrót: niedziela, 25 grudnia 2016, 7: 00am

Konwertuj datę / czas na czas LA

moment.utc('2016-12-25 07:00').tz('America/Los_Angeles').format('ddd, Do MMMM YYYY, h:mma');

Zwroty: so, 24th December 2016, 11:00pm

Konwertuj z czasu LA do Londynu

moment.tz('2016-12-25 07:00', 'America/Los_Angeles').tz('Europe/London').format( 'ddd, Do MMMM YYYY, h:mma' );

Powrót: Nie, 25 grudnia 2016, 15:00

 1
Author: omarjebari,
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-13 12:08:46

Istnieje moduł npm o nazwie 'timezones.json ' możesz użyć do tego; w zasadzie składa się z pliku json z obiektami zawierającymi informacje na temat czasu letniego i przesunięcia,....

Dla Azji/Dżakarty będzie można zwrócić ten obiekt:

{
  "value": "SE Asia Standard Time",
  "abbr": "SAST",
  "offset": 7,
  "isdst": false,
  "text": "(UTC+07:00) Bangkok, Hanoi, Jakarta",
  "utc": [
    "Antarctica/Davis",
    "Asia/Bangkok",
    "Asia/Hovd",
    "Asia/Jakarta",
    "Asia/Phnom_Penh",
    "Asia/Pontianak",
    "Asia/Saigon",
    "Asia/Vientiane",
    "Etc/GMT-7",
    "Indian/Christmas"
  ]
}

Znajdziesz go tutaj:

Https://github.com/dmfilipenko/timezones.json

Https://www.npmjs.com/package/timezones.json

Hope it ' s useful

 0
Author: Kevin,
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-07-25 06:04:21

Przesunięcie strefy czasowej dla bieżącej strefy czasowej

date +%s -d '1 Jan 1970'

Dla mojej strefy czasowej GMT + 10 (Australia) zwrócono -36000

 0
Author: anthony,
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-15 04:49:47

Ostatnio zrobiłem to w maszynopisie:

// fromTimezone example : Europe/Paris, toTimezone example: Europe/London
private calcTime( fromTimezone: string, toTimezone: string, dateFromTimezone: Date ): Date {
  const dateToGetOffset = new Date( 2018, 5, 1, 12 );

  const fromTimeString = dateToGetOffset.toLocaleTimeString( "en-UK", { timeZone: fromTimezone, hour12: false } );
  const toTimeString = dateToGetOffset.toLocaleTimeString( "en-UK", { timeZone: toTimezone, hour12: false } );

  const fromTimeHours: number = parseInt( fromTimeString.substr( 0, 2 ), 10 );
  const toTimeHours: number = parseInt( toTimeString.substr( 0, 2 ), 10 );

  const offset: number = fromTimeHours - toTimeHours;

  // convert to msec
  // add local time zone offset
  // get UTC time in msec
  const dateFromTimezoneUTC = Date.UTC( dateFromTimezone.getUTCFullYear(),
    dateFromTimezone.getUTCMonth(),
    dateFromTimezone.getUTCDate(),
    dateFromTimezone.getUTCHours(),
    dateFromTimezone.getUTCMinutes(),
    dateFromTimezone.getUTCSeconds(),
  );

  // create new Date object for different city
  // using supplied offset
  const dateUTC = new Date( dateFromTimezoneUTC + ( 3600000 * offset ) );

  // return time as a string
  return dateUTC;
}

Używam formatu" en-UK", ponieważ jest prosty. To mogło być "en-US" albo cokolwiek działa.

Jeśli pierwszy argument jest Twoją lokalną strefą czasową, a seconde jest docelową strefą czasową, zwraca obiekt Date z prawidłowym przesunięciem.

 0
Author: Alexandre Liscia,
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-05-29 15:57:14

Nie znam łatwej metody konwersji obiektu daty na dowolną strefę czasową, ale jeśli chcesz przekonwertować go na lokalną strefę czasową, możesz po prostu przekonwertować go za pomocą Date.prototype.getTime() na odpowiednią liczbę milisekund i z powrotem.

date = new Date('2016-05-24T13:07:20');
date = new Date(date.getTime());

Na przykład, date.getHours() powróci teraz 15 zamiast 13, Jeśli jesteś, tak jak ja, w Austrii (a jest lato).

Czytałem, że różne funkcje datetime mogą wykazywać niestandardowe zachowanie w niektórych przeglądarkach, więc najpierw przetestuj to. Mogę sprawdź, czy działa w Chrome.

 -1
Author: 黄雨伞,
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-05-24 13:22:59