문자열 표현을 사용하지 않고 설정된 시간대로 날짜 만들기


412

일, 월 및 연도에 대한 3 개의 드롭 다운이있는 웹 페이지가 있습니다. Date숫자를 취하는 JavaScript 생성자를 사용하면 Date현재 시간대에 대한 객체를 얻습니다 .

new Date(xiYear, xiMonth, xiDate)

정확한 날짜를 알려주십시오. 그러나 일광 절약 시간제 때문에 날짜가 GMT + 01 : 00이라고 생각합니다.

여기서 문제는 이것을 DateAjax 메소드에 전달 하고 서버에서 날짜가 직렬화 해제되면 GMT로 변환되어 하루가 한 시간 뒤로 이동하는 시간이 없어진다는 것입니다. 이제 일, 월, 년을 개별적으로 Ajax 방법으로 전달할 수는 있지만 더 나은 방법이 있어야합니다.

받아 들여진 대답은 올바른 방향으로 나를 지적했지만, setUTCHours()그 자체 만 사용하면 변경되었습니다.

Apr 5th 00:00 GMT+01:00 

에

Apr 4th 23:00 GMT+01:00

그런 다음 UTC 날짜, 월 및 연도를 설정해야했습니다.

Apr 5th 01:00 GMT+01:00

내가 원하는 것입니다.


9
수락 된 답변이 올바른 방향을 제시했지만 귀하의 질문에 답변하지 않은 경우 수락 된 답변이 아니어야한다고 주장합니다. 답변은 질문에 대한 답변이되어야합니다.
— TWR Cole

답변:


481

사용 .setUTCHours()이하면 시스템 전체 UTC-시간을 사용할 수 있도록 할 UTC 타임 실제로 설정 날짜, 할 수있을 것입니다.

날짜 문자열을 지정하지 않으면 생성자에서 UTC를 사용하여 설정할 수 없습니다.

를 사용 new Date(Date.UTC(year, month, day, hour, minute, second))하면 특정 UTC 시간에서 Date 객체를 만들 수 있습니다.


101
"new Date (Date.UTC (...))"구문을 사용하면 UTC를 나타내는 특정 시점을 기준으로 UTC 날짜 와 동일한 날짜를 작성할 수 있지만 동일하지는 않습니다. UTC가 아닌 시간대가 다릅니다.
— Anthony

52
"Date"를 사용할 때 "month"-값의 범위는 0-11 (1-12 아님)입니다. 나는 2 시간 (1 시간이되어야했지만)의 시간대 오프셋을 계속 얻었고 그 이유가 잘못된 달이라는 것을 알기까지 몇 시간이 걸렸다.
— Select0r

4
이 답변은 훌륭합니다. 그러나 나는 많은 장소에서 새로운 날짜를 사용하는 라이브러리 [datepicker ui]를 사용하고 있습니다. 내가 원하는 것은 UTC 시간대를 설정하는 것이며 모든 날짜는 새 시간대를 기준으로합니다. Javascript가 이것에 대해 아무것도 없다는 것에 놀랐습니다.
— Sanjeev Kumar Dangi

6
@jishi-날짜 객체는 현지 시간이 아닌 UTC 시간 값을 기반으로합니다. 그러나 기본 Date.prototype.toString 메서드는 현지 시간 값 을 표시 합니다.
— RobG

5
@ Anthony— " 하지만 동시에 는 아닙니다"는 정확하지 않습니다. 시간과 정확히 같은 순간을 나타내며 유일한 차이점은 시간대 오프셋입니다.
— RobG

198
var d = new Date(xiYear, xiMonth, xiDate);
d.setTime( d.getTime() + d.getTimezoneOffset()*60*1000 );

이 답변은 원래 질문에 특별히 맞춰져 있으며 반드시 예상되는 답변을 제공하지는 않습니다. 특히 일부 사람들은 시간대 오프셋을 더하는 대신 빼기를 원할 것입니다. 이 솔루션의 요점은 특정 deserialization을 위해 javascript의 날짜 객체를 해킹하는 것이지만 모든 경우에 정확하지는 않습니다.


62
물론 @gthmb이지만 *60*1000이 경우에는 더 명확 하다고 생각합니다 . 다시 말해서, 그것이 왜 존재하는지는 자명하다.
— TWR Cole

22
내 시간대에 적합한 시간을 얻으려면 + (플러스) 대신-(빼기)를 사용해야한다는 점을 제외하고는 거의 나에게 효과적입니다.
— Wytze

3
예, 다른 사람들이 지적했듯이-이 답변에 실수가 있다고 생각합니다. 마이너스가 아니어야합니다.
— UpTheCreek

3
developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… 에 따르면 getTimezoneOffset에 의해 리턴 된 값은 DST를 고려하여 함수를 호출 할 때 로케일의 실제 오프셋에 따라 서명됩니다. 왜 당신이 그것을 빼야하는지 이해하지 못합니다.
— TWR Cole

15
timezoneOffset을 날짜 객체에 추가하면 로컬 시간대로 형식이 지정된 값은 UTC의 올바른 값처럼 보이지만 원래 시간대 오프셋은 그대로 유지됩니다 ( "ISOString"과 같은 일부 표현이 실제로 표시됨). 따라서 날짜 객체를 직렬화하는 방법에 따라 JS는 표준 시간대 오프셋을 다시 적용 하여 잘못된 답변을 줄 수 있습니다. 나는 이것이 +/- 사이의 주석에서 혼란을 초래한다고 생각합니다. 어쨌든, 나의 downvote는이 사실과 "대부분의 경우 당신이 기대하는 것을 얻습니다"입니다.
— metamatt

173

createDateAsUTC 함수 가 필요하다고 생각합니다 ( convertDateToUTC 와 비교 하십시오 )

function createDateAsUTC(date) {
    return new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()));
}

function convertDateToUTC(date) { 
    return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds()); 
}

36
나는 그의 대답의 명확성과 도움에 놀랐습니다. S : 자바 스크립트 날짜와 함께 작업하는 오늘까지 그런 악몽 몰랐습니다
— will824

이 둘의 차이점을 설명할까요? 첫 번째는 dateUTC 시간대 로 변환 되지만 두 번째는 유용한 기능이없는 것 같습니다. (와 같은 날짜를 반환합니다 date)
— Jonathan Lin

4
나는 그것을 얻는다 : 첫 번째는 UTC 시간대의 날짜를 현지 시간의 리터럴 날짜 값과 함께 반환합니다. 두 번째는 현지 시간대로 날짜를 반환하지만 UTC 리터럴 날짜 값을 사용합니다.
— Jonathan Lin

8
이 접근 방식은 "epoch shifting"이라는 패턴을 구현 한 것으로, 현재 시간대 오프셋에 의해 시프트 된 에포크 (UTC 기반)를 이동시키기위한 것입니다. 불행히도, 이것이 일반적으로 보이지만,이 접근법은 결함이있다. JavaScript의 Date객체는 항상 UTC 기반 유닉스 시대와 현지 시간대를 반영합니다 . toString결과 날짜 개체 를 호출 할 때 UTC로 예상 되더라도 여전히 현지 시간대를 볼 때 증상이 나타납니다 .
— Matt Johnson-Pint

2
또한 현지 시간대의 일광 절약 시간제 전환 근처에서 시간 값에 오류가 발생할 수 있습니다. 요컨대, (구현을 통한) 에포크 시프 팅은 JavaScript Date객체에서 작동하지 않습니다 . 여기에서 보는 또 다른 방법은 Date.UTCUTC 기반 값 을 예상하고 현지 시간 값을 제공하고 Date생성자 와 함께 제공하는 것 입니다.
— Matt Johnson-Pint

70

시간대를 설정하고 다시 확인하기 만하면됩니다.

new Date().toLocaleString("en-US", {timeZone: "America/New_York"})

다른 시간대 는 다음과 같습니다

var world_timezones =
[
    'Europe/Andorra',
    'Asia/Dubai',
    'Asia/Kabul',
    'Europe/Tirane',
    'Asia/Yerevan',
    'Antarctica/Casey',
    'Antarctica/Davis',
    'Antarctica/DumontDUrville', 
    'Antarctica/Mawson',
    'Antarctica/Palmer',
    'Antarctica/Rothera',
    'Antarctica/Syowa',
    'Antarctica/Troll',
    'Antarctica/Vostok',
    'America/Argentina/Buenos_Aires',
    'America/Argentina/Cordoba',
    'America/Argentina/Salta',
    'America/Argentina/Jujuy',
    'America/Argentina/Tucuman',
    'America/Argentina/Catamarca',
    'America/Argentina/La_Rioja',
    'America/Argentina/San_Juan',
    'America/Argentina/Mendoza',
    'America/Argentina/San_Luis',
    'America/Argentina/Rio_Gallegos',
    'America/Argentina/Ushuaia',
    'Pacific/Pago_Pago',
    'Europe/Vienna',
    'Australia/Lord_Howe',
    'Antarctica/Macquarie',
    'Australia/Hobart',
    'Australia/Currie',
    'Australia/Melbourne',
    'Australia/Sydney',
    'Australia/Broken_Hill',
    'Australia/Brisbane',
    'Australia/Lindeman',
    'Australia/Adelaide',
    'Australia/Darwin',
    'Australia/Perth',
    'Australia/Eucla',
    'Asia/Baku',
    'America/Barbados',
    'Asia/Dhaka',
    'Europe/Brussels',
    'Europe/Sofia',
    'Atlantic/Bermuda',
    'Asia/Brunei',
    'America/La_Paz',
    'America/Noronha',
    'America/Belem',
    'America/Fortaleza',
    'America/Recife',
    'America/Araguaina',
    'America/Maceio',
    'America/Bahia',
    'America/Sao_Paulo',
    'America/Campo_Grande',
    'America/Cuiaba',
    'America/Santarem',
    'America/Porto_Velho',
    'America/Boa_Vista',
    'America/Manaus',
    'America/Eirunepe',
    'America/Rio_Branco',
    'America/Nassau',
    'Asia/Thimphu',
    'Europe/Minsk',
    'America/Belize',
    'America/St_Johns',
    'America/Halifax',
    'America/Glace_Bay',
    'America/Moncton',
    'America/Goose_Bay',
    'America/Blanc-Sablon',
    'America/Toronto',
    'America/Nipigon',
    'America/Thunder_Bay',
    'America/Iqaluit',
    'America/Pangnirtung',
    'America/Atikokan',
    'America/Winnipeg',
    'America/Rainy_River',
    'America/Resolute',
    'America/Rankin_Inlet',
    'America/Regina',
    'America/Swift_Current',
    'America/Edmonton',
    'America/Cambridge_Bay',
    'America/Yellowknife',
    'America/Inuvik',
    'America/Creston',
    'America/Dawson_Creek',
    'America/Fort_Nelson',
    'America/Vancouver',
    'America/Whitehorse',
    'America/Dawson',
    'Indian/Cocos',
    'Europe/Zurich',
    'Africa/Abidjan',
    'Pacific/Rarotonga',
    'America/Santiago',
    'America/Punta_Arenas',
    'Pacific/Easter',
    'Asia/Shanghai',
    'Asia/Urumqi',
    'America/Bogota',
    'America/Costa_Rica',
    'America/Havana',
    'Atlantic/Cape_Verde',
    'America/Curacao',
    'Indian/Christmas',
    'Asia/Nicosia',
    'Asia/Famagusta',
    'Europe/Prague',
    'Europe/Berlin',
    'Europe/Copenhagen',
    'America/Santo_Domingo',
    'Africa/Algiers',
    'America/Guayaquil',
    'Pacific/Galapagos',
    'Europe/Tallinn',
    'Africa/Cairo',
    'Africa/El_Aaiun',
    'Europe/Madrid',
    'Africa/Ceuta',
    'Atlantic/Canary',
    'Europe/Helsinki',
    'Pacific/Fiji',
    'Atlantic/Stanley',
    'Pacific/Chuuk',
    'Pacific/Pohnpei',
    'Pacific/Kosrae',
    'Atlantic/Faroe',
    'Europe/Paris',
    'Europe/London',
    'Asia/Tbilisi',
    'America/Cayenne',
    'Africa/Accra',
    'Europe/Gibraltar',
    'America/Godthab',
    'America/Danmarkshavn',
    'America/Scoresbysund',
    'America/Thule',
    'Europe/Athens',
    'Atlantic/South_Georgia',
    'America/Guatemala',
    'Pacific/Guam',
    'Africa/Bissau',
    'America/Guyana',
    'Asia/Hong_Kong',
    'America/Tegucigalpa',
    'America/Port-au-Prince',
    'Europe/Budapest',
    'Asia/Jakarta',
    'Asia/Pontianak',
    'Asia/Makassar',
    'Asia/Jayapura',
    'Europe/Dublin',
    'Asia/Jerusalem',
    'Asia/Kolkata',
    'Indian/Chagos',
    'Asia/Baghdad',
    'Asia/Tehran',
    'Atlantic/Reykjavik',
    'Europe/Rome',
    'America/Jamaica',
    'Asia/Amman',
    'Asia/Tokyo',
    'Africa/Nairobi',
    'Asia/Bishkek',
    'Pacific/Tarawa',
    'Pacific/Enderbury',
    'Pacific/Kiritimati',
    'Asia/Pyongyang',
    'Asia/Seoul',
    'Asia/Almaty',
    'Asia/Qyzylorda',
    'Asia/Qostanay', 
    'Asia/Aqtobe',
    'Asia/Aqtau',
    'Asia/Atyrau',
    'Asia/Oral',
    'Asia/Beirut',
    'Asia/Colombo',
    'Africa/Monrovia',
    'Europe/Vilnius',
    'Europe/Luxembourg',
    'Europe/Riga',
    'Africa/Tripoli',
    'Africa/Casablanca',
    'Europe/Monaco',
    'Europe/Chisinau',
    'Pacific/Majuro',
    'Pacific/Kwajalein',
    'Asia/Yangon',
    'Asia/Ulaanbaatar',
    'Asia/Hovd',
    'Asia/Choibalsan',
    'Asia/Macau',
    'America/Martinique',
    'Europe/Malta',
    'Indian/Mauritius',
    'Indian/Maldives',
    'America/Mexico_City',
    'America/Cancun',
    'America/Merida',
    'America/Monterrey',
    'America/Matamoros',
    'America/Mazatlan',
    'America/Chihuahua',
    'America/Ojinaga',
    'America/Hermosillo',
    'America/Tijuana',
    'America/Bahia_Banderas',
    'Asia/Kuala_Lumpur',
    'Asia/Kuching',
    'Africa/Maputo',
    'Africa/Windhoek',
    'Pacific/Noumea',
    'Pacific/Norfolk',
    'Africa/Lagos',
    'America/Managua',
    'Europe/Amsterdam',
    'Europe/Oslo',
    'Asia/Kathmandu',
    'Pacific/Nauru',
    'Pacific/Niue',
    'Pacific/Auckland',
    'Pacific/Chatham',
    'America/Panama',
    'America/Lima',
    'Pacific/Tahiti',
    'Pacific/Marquesas',
    'Pacific/Gambier',
    'Pacific/Port_Moresby',
    'Pacific/Bougainville',
    'Asia/Manila',
    'Asia/Karachi',
    'Europe/Warsaw',
    'America/Miquelon',
    'Pacific/Pitcairn',
    'America/Puerto_Rico',
    'Asia/Gaza',
    'Asia/Hebron',
    'Europe/Lisbon',
    'Atlantic/Madeira',
    'Atlantic/Azores',
    'Pacific/Palau',
    'America/Asuncion',
    'Asia/Qatar',
    'Indian/Reunion',
    'Europe/Bucharest',
    'Europe/Belgrade',
    'Europe/Kaliningrad',
    'Europe/Moscow',
    'Europe/Simferopol',
    'Europe/Kirov',
    'Europe/Astrakhan',
    'Europe/Volgograd',
    'Europe/Saratov',
    'Europe/Ulyanovsk',
    'Europe/Samara',
    'Asia/Yekaterinburg',
    'Asia/Omsk',
    'Asia/Novosibirsk',
    'Asia/Barnaul',
    'Asia/Tomsk',
    'Asia/Novokuznetsk',
    'Asia/Krasnoyarsk',
    'Asia/Irkutsk',
    'Asia/Chita',
    'Asia/Yakutsk',
    'Asia/Khandyga',
    'Asia/Vladivostok',
    'Asia/Ust-Nera',
    'Asia/Magadan',
    'Asia/Sakhalin',
    'Asia/Srednekolymsk',
    'Asia/Kamchatka',
    'Asia/Anadyr',
    'Asia/Riyadh',
    'Pacific/Guadalcanal',
    'Indian/Mahe',
    'Africa/Khartoum',
    'Europe/Stockholm',
    'Asia/Singapore',
    'America/Paramaribo',
    'Africa/Juba',
    'Africa/Sao_Tome',
    'America/El_Salvador',
    'Asia/Damascus',
    'America/Grand_Turk',
    'Africa/Ndjamena',
    'Indian/Kerguelen',
    'Asia/Bangkok',
    'Asia/Dushanbe',
    'Pacific/Fakaofo',
    'Asia/Dili',
    'Asia/Ashgabat',
    'Africa/Tunis',
    'Pacific/Tongatapu',
    'Europe/Istanbul',
    'America/Port_of_Spain',
    'Pacific/Funafuti',
    'Asia/Taipei',
    'Europe/Kiev',
    'Europe/Uzhgorod',
    'Europe/Zaporozhye',
    'Pacific/Wake',
    'America/New_York',
    'America/Detroit',
    'America/Kentucky/Louisville',
    'America/Kentucky/Monticello',
    'America/Indiana/Indianapolis',
    'America/Indiana/Vincennes',
    'America/Indiana/Winamac',
    'America/Indiana/Marengo',
    'America/Indiana/Petersburg',
    'America/Indiana/Vevay',
    'America/Chicago',
    'America/Indiana/Tell_City',
    'America/Indiana/Knox',
    'America/Menominee',
    'America/North_Dakota/Center',
    'America/North_Dakota/New_Salem',
    'America/North_Dakota/Beulah',
    'America/Denver',
    'America/Boise',
    'America/Phoenix',
    'America/Los_Angeles',
    'America/Anchorage',
    'America/Juneau',
    'America/Sitka',
    'America/Metlakatla',
    'America/Yakutat',
    'America/Nome',
    'America/Adak',
    'Pacific/Honolulu',
    'America/Montevideo',
    'Asia/Samarkand',
    'Asia/Tashkent',
    'America/Caracas',
    'Asia/Ho_Chi_Minh',
    'Pacific/Efate',
    'Pacific/Wallis',
    'Pacific/Apia',
    'Africa/Johannesburg'
];

8
이 상단에 길을해야한다
— 유진

일부 브라우저에서는이 기능이 작동하지 않습니다. 예 : IE11.
— Paul LeBeau

IE 콘솔 오류 : 'timeZone'에 대한 옵션 값 'AMERICA / NEW_YORK'이 (가) 유효한 범위를 벗어났습니다. 예상 : [ 'UTC'] @OloghoCyrilPaul
— Matee Gojra

1
매우 쉽고 매우 우아합니다. 당신은 여기에 시간대의 모든과 목록 찾을 수 stackoverflow.com/questions/38399465/...을 . UTC의 경우 런던 시간대를 선택하십시오.
— EPurpl3

1
이러한 값 중 어느 것도 "시간대"가 아니며 , 동일한 역사적인 현지 시간대 및 일광 절약 시간제 변경이있는 장소의 IANA 시간대 데이터베이스 대표 위치입니다.
— RobG

28

이것이 가능하지 않다고 생각합니다. Date 객체를 만든 후에 시간대를 설정할 수는 없습니다.

그리고 이것은 개념적으로 (어쩌면 구현되지 않은 경우) 의미가 있습니다. 당 http://en.wikipedia.org/wiki/Unix_timestamp (강조 광산) :

유닉스 시간 또는 POSIX 시간은 1970 년 1 월 1 일 목요일 자정 협정 세계시 (UTC) 이후 경과 된 시간 ( 초)으로 정의 된 시간을 설명하는 시스템입니다 .

하나를 구성하면 "실시간"의 특정 지점을 나타냅니다. 시간대는 해당 추상 시점을 사람이 읽을 수있는 문자열로 변환하려는 경우에만 관련이 있습니다.

따라서 생성자에서 Date가 나타내는 실제 시간 만 변경할 수 있습니다. 안타깝게도 명시적인 시간대를 전달할 수있는 방법이없는 것 같습니다. 호출하는 생성자 (정확하게는 올바른)는 "현지"시간 변수를 표준 시간대로 저장할 때 GMT로 변환하므로 int, int, int생성자 를 사용할 수있는 방법이 없습니다. GMT 시간.

더하기 측면에서는 대신 String을 사용하는 생성자를 사용하는 것이 쉽지 않습니다. 숫자 달을 문자열 (최소한 Firefox에서는)로 변환 할 필요조차 없으므로 순진한 구현이 작동하기를 바랐습니다. 그러나 그것을 시도한 후에는 Firefox, Chrome 및 Opera에서 성공적으로 작동하지만 Konqueror ( "Invalid Date"), Safari ( "Invalid Date") 및 IE ( "NaN")에서는 실패합니다. 월을 문자열로 변환하는 조회 배열이 있다고 가정합니다.

var months = [ '', 'January', 'February', ..., 'December'];

function createGMTDate(xiYear, xiMonth, xiDate) {
   return new Date(months[xiMonth] + ' ' + xiDate + ', ' + xiYear + ' 00:00:00 GMT');
}

6
방법가 존재하지 않는 경우는 Date 객체의 시간대를 설정하는 방법이 있음을 암시하고있다 "만든 후 Date 객체의 시간대를 설정" 으로 이 생성 될이? js 날짜가 "Epoch 이후 몇 초 정도의 얇은 래퍼"인 것처럼 보이지 않습니다. 초 수와 시간대를 더한 것 같습니다.
— Anthony

1
@Anthony, 클라이언트의 시간대 만 사용할 수 있습니다. Javascript는 utc에 대해 로컬로 수행 할 수 있지만 시간대 데이터베이스에 액세스 할 수 없습니다. 예를 들어, 샌디에고에있을 때는 멕시코 시티의 시간을 알 수 없습니다.
— Samuel Danielson


16

시간대를 포함하여 연도, 월, 일 등에서 Javascript Date 객체를 생성하는 약간 다르지만 관련이있는 문제 를 처리하려는 경우 (즉, 문자열을 Date로 구문 분석하려는 경우) 명백하게 복잡한 춤을 추어 야한다 :

// parseISO8601String : string -> Date
// Parse an ISO-8601 date, including possible timezone,
// into a Javascript Date object.
//
// Test strings: parseISO8601String(x).toISOString()
// "2013-01-31T12:34"              -> "2013-01-31T12:34:00.000Z"
// "2013-01-31T12:34:56"           -> "2013-01-31T12:34:56.000Z"
// "2013-01-31T12:34:56.78"        -> "2013-01-31T12:34:56.780Z"
// "2013-01-31T12:34:56.78+0100"   -> "2013-01-31T11:34:56.780Z"
// "2013-01-31T12:34:56.78+0530"   -> "2013-01-31T07:04:56.780Z"
// "2013-01-31T12:34:56.78-0330"   -> "2013-01-31T16:04:56.780Z"
// "2013-01-31T12:34:56-0330"      -> "2013-01-31T16:04:56.000Z"
// "2013-01-31T12:34:56Z"          -> "2013-01-31T12:34:56.000Z"
function parseISO8601String(dateString) {
    var timebits = /^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2})(?::([0-9]*)(\.[0-9]*)?)?(?:([+-])([0-9]{2})([0-9]{2}))?/;
    var m = timebits.exec(dateString);
    var resultDate;
    if (m) {
        var utcdate = Date.UTC(parseInt(m[1]),
                               parseInt(m[2])-1, // months are zero-offset (!)
                               parseInt(m[3]),
                               parseInt(m[4]), parseInt(m[5]), // hh:mm
                               (m[6] && parseInt(m[6]) || 0),  // optional seconds
                               (m[7] && parseFloat(m[7])*1000) || 0); // optional fraction
        // utcdate is milliseconds since the epoch
        if (m[9] && m[10]) {
            var offsetMinutes = parseInt(m[9]) * 60 + parseInt(m[10]);
            utcdate += (m[8] === '+' ? -1 : +1) * offsetMinutes * 60000;
        }
        resultDate = new Date(utcdate);
    } else {
        resultDate = null;
    }
    return resultDate;
}

즉, 시간대가없는 날짜를 사용하여 'UTC 시간'을 생성하므로 UTC가있는 로케일을 알 수 있습니다 (예 : UTC '로케일'및 로컬로 기본 설정되지 않음) 표시된 시간대 오프셋을 수동으로 적용하십시오.

누군가가 실제로 자바 스크립트 날짜 객체에 대해 5 분 이상 생각 했다면 좋지 않을 것입니다 ....


1
훌륭한 기능에 감사드립니다! 내가 바꿀 유일한 것은 시간대 오프셋에서 콜론에 대한 지원을 추가하는 것입니다. var 타임 비트 = / ^ ([0-9] {4})-([0-9] {2})-([0-9] {2}) T ([0-9] {2}) :( [0-9] {2}) (? :: ([0-9] *) (\. [0-9] *)?)? (? : ([+-]) ([0-9] { 2} [:]?) ([0-9] {2}))? /;
— robnardo

2
그들은 그것에 대해 생각했다; 불행히도 JS는 초기 구현을 위해 Java의 Date 클래스를 복사했기 때문에 "그들"은 Java 언어 디자이너였습니다.
— Xanthir

@Xanthir Oooh, 맞습니다. 원래 Java Date 객체가 얼마나 끔찍했는지 잊었습니다. 그러나 적어도 Java는 그것을 더 이상 사용하지 않고 넘어갔습니다 .Javascript는 할 수없는 것 같습니다 (기괴한 언어, Javascript : 오히려 귀엽고 처음에는 거의 끔찍하지 않습니다).
— 노먼 그레이

13
d = new Date();
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
nd = new Date(utc + (3600000*offset));

offset value base on which location time zone you would like to set 
For India offset value +5.5,
New York offset value -4,
London offset value +1

모든 위치 오프셋 Wiki UTC 시간 오프셋 목록


일광 절약 시간제에 뉴욕에 어떤 도움이됩니까?
— frederj

뉴욕의 경우 오프셋 값 -4를 사용하십시오
— Vijay Lathiya

1
뉴욕의 오프셋은 일광 절약 시간제에 따라 다릅니다. 때로는 -4이고 때로는 -5입니다. en.wikipedia.org/wiki/Eastern_Time_Zone
— frederj

8

getTimeZoneOffset은 UTC + z에 대한 빼기입니다.

var d = new Date(xiYear, xiMonth, xiDate);
if(d.getTimezoneOffset() > 0){
    d.setTime( d.getTime() + d.getTimezoneOffset()*60*1000 );
}

1
약간의 실수,! = 0 not> 0. 나는 이것을 사용하여 끝났다
— Cristi Băluță

8

이것은 누군가에게 도움이 될 수 있습니다. 새로운 생성자에 전달한 내용의 끝에 UTC를 넣으십시오.

적어도 크롬에서는 말할 수 있습니다. var date = new Date("2014-01-01 11:00:00 UTC")


1
Safari에서 "잘못된 날짜"를 반환합니다
— pmrotule

1
`UTC`를 +0000(00과 UTC 사이의 공백을 제거해야 함을 알 수 있음)으로 바꾸면 Firefox와 Chrome 모두에서 작동합니다. 그래도 Safari는 확실하지 않습니다. (참조 : stackoverflow.com/a/17545854/1273587 )
— cytsunny

8

한 줄 솔루션

new Date(new Date(1422524805305).getTime() - 330*60*1000)

1422524805305 대신 시간 소인 (밀리 초)을 사용하십시오. 330 대신 시간대 오프셋 (분)을 사용하십시오. GMT (예 : 인도 +5 : 30은 5 * 60 + 30 = 330 분)


4
이것은 클라이언트에서 실행되는 코드입니다. 즉, 시간대가 다른 위치의 사용자와 다를 수 있습니다. 이 솔루션을 사용하려면 필요한 모든 사람이 동일한 시간대 (귀하의)에 거주해야합니다.
— Kevin Beal

이 경우 @Kevin Beal은 getTimezoneOffset을 사용하십시오
— Maximus

6
// My clock 2018-07-25, 00:26:00 (GMT+7)
let date = new Date(); // 2018-07-24:17:26:00 (Look like GMT+0)
const myTimeZone = 7; // my timeZone 
// my timeZone = 7h = 7 * 60 * 60 * 1000 (millisecond);
// 2018-07-24:17:26:00 = x (milliseconds)
// finally, time in milliseconds (GMT+7) = x + myTimezone 
date.setTime( date.getTime() + myTimeZone * 60 * 60 * 1000 );
// date.toISOString() = 2018-07-25, 00:26:00 (GMT+7)

코드를 설명하고 문제를 해결하는 방법은 답변의 품질을 높이고 사용자 학습에 도움이됩니다.
— Nic3500

5

올바른 날짜를 얻는 가장 쉬운 방법은 datejs를 사용하는 것입니다.

http://www.datejs.com/

이 형식으로 Ajax를 통해 날짜를 문자열로 표시합니다 : '2016-01-12T00 : 00 : 00'

var yourDateString = '2016-01-12T00:00:00';
var yourDate = new Date(yourDateString);
console.log(yourDate);
if (yourDate.getTimezoneOffset() > 0){
    yourDate = new Date(yourDateString).addMinutes(yourDate.getTimezoneOffset());
}
console.log(yourDate);

콘솔은 다음을 읽습니다 :

2016 년 1 월 11 일 월요일 19:00:00 GMT-0500 (동부 표준시)

화 1 월 12 일 2016 00:00:00 GMT-0500 (동부 표준시)

https://jsfiddle.net/vp1ena7b/3/

'addMinutes'는 datejs에서 온 것입니다. 아마도 순수 js에서 직접 할 수는 있지만 이미 프로젝트에 datejs가 있으므로 올바른 날짜를 얻는 데 사용할 수있는 방법을 찾았습니다.

나는 이것이 누군가를 도울 것이라고 생각했다 ...


모든 방법을 시험해 보았는데 이것은 자정을 얻는 유일한 방법이었습니다.
— SharpC

3

어떤 마일리지

var d = new Date(xiYear, xiMonth, xiDate).toLocaleString();

이것은 나를 위해 트릭을 수행하는 것처럼 보이지만 (GMT에서 한 시간대 떨어져 있음) "로케일"은 반드시 시간대와 관련이 없기 때문에 그것에 의존하지는 않습니다.
— Wytze

3

이 코드는 브라우저 시간대로 형식화 된 Date 객체 를 반환합니다 .

Date.prototype.timezone = function () {
    this.setHours(this.getHours() + (new Date().getTimezoneOffset() / 60));
    return this;
}

편집하다:

Date API를 오염시키지 않기 위해 위의 함수를 유틸리티 함수로 변환 할 수 있습니다. 이 함수는 Date 객체를 가져 와서 변형 된 Date 객체를 반환합니다.

function setTimeZone(date) {
    date.setHours(date.getHours() + (new Date().getTimezoneOffset() / 60));
    return date;
}

6
네이티브 객체 확장 불가
— Paul Rumkin

1

내가 본 최고의 솔루션은

http://www.codingforums.com/archive/index.php/t-19663.html

인쇄 시간 기능

<script language="javascript" type="text/javascript">
//borrowed from echoecho
//http://www.echoecho.com/ubb/viewthread.php?tid=2362&pid=10482&#pid10482
workDate = new Date()
UTCDate = new Date()
UTCDate.setTime(workDate.getTime()+workDate.getTimezoneOffset()*60000)

function printTime(offset) {
    offset++;
    tempDate = new Date()
    tempDate.setTime(UTCDate.getTime()+3600000*(offset))
    timeValue = ((tempDate.getHours()<10) ? ("0"+tempDate.getHours()) : (""+tempDate.getHours()))
    timeValue += ((tempDate.getMinutes()<10) ? ("0"+tempDate.getMinutes()) : tempDate.getMinutes())
    timeValue += " hrs."
    return timeValue
    }
    var now = new Date()
    var seed = now.getTime() % 0xfffffff
    var same = rand(12)
</script>

Banff, Canada:
<script language="JavaScript">document.write(printTime("-7"))</script>

전체 코드 예

<html>

<head>
<script language="javascript" type="text/javascript">
//borrowed from echoecho
//http://www.echoecho.com/ubb/viewthread.php?tid=2362&pid=10482&#pid10482
workDate = new Date()
UTCDate = new Date()
UTCDate.setTime(workDate.getTime()+workDate.getTimezoneOffset()*60000)

function printTime(offset) {
offset++;
tempDate = new Date()
tempDate.setTime(UTCDate.getTime()+3600000*(offset))
timeValue = ((tempDate.getHours()<10) ? ("0"+tempDate.getHours()) : (""+tempDate.getHours()))
timeValue += ((tempDate.getMinutes()<10) ? ("0"+tempDate.getMinutes()) : tempDate.getMinutes())
timeValue += " hrs."
return timeValue
}
var now = new Date()
var seed = now.getTime() % 0xfffffff
var same = rand(12)
</script>

</head>

<body>
Banff, Canada:
<script language="JavaScript">document.write(printTime("-7"))</script>
<br>
Michigan:
<script language="JavaScript">document.write(printTime("-5"))</script>
<br>
Greenwich, England(UTC):
<script language="JavaScript">document.write(printTime("-0"))</script>
<br>
Tokyo, Japan:
<script language="JavaScript">document.write(printTime("+9"))</script>
<br>
Berlin, Germany:
<script language="JavaScript">document.write(printTime("+1"))</script>

</body>
</html>

귀하의 예는 일광 절약 시간제를 제외합니다. 현재 시간 : 2013 년 10 월 4 일 (금) GMT-0700 (태평양 일광 절약 시간) Utc 시간 : 2013 년 10 월 4 일 (금) 18:13:43 GMT 밴프, 캐나다 : 1213 시간. 미시간 : 1413 시간 영국 그리니치 (UTC) : 1913 시간 일본 도쿄 : 0413 시간 독일 베를린 : 2013 시간
— Jeson Martajaya

0

두 날짜 사이의 시간 차이를 확인하려면 두 번째 시간대가 원하는 첫 번째 시간대보다 작은 지 확인하고 시간을 빼거나 추가하면됩니다.

  const currTimezone = new Date().getTimezoneOffset(); // your timezone
  const newDateTimezone = date.getTimezoneOffset(); // date with unknown timezone

  if (currTimezone !== newDateTimezone) {
    // and below you are checking if difference should be - or +. It depends on if unknown timezone is lesser or greater than yours
    const newTimezone = (currTimezone - newDateTimezone) * (currTimezone > newDateTimezone ? 1 : -1);
    date.setTime(date.getTime() + (newTimezone * 60 * 1000));
  }

0

GMT -03 : 00 예

new Date(new Date()-3600*1000*3).toISOString();  // 2020-02-27T15:03:26.261Z

또는

now  = new Date().getTime()-3600*1000*3; // 1582818380528
data = new Date(now).toISOString();      // 2020-02-27T15:03:26.261Z

-1

이것은 나를 위해 일했습니다. 그래도 좋은 아이디어인지 확실하지 않습니다.

var myDate = new Date();
console.log('myDate:', myDate);   // myDate: "2018-04-04T01:09:38.112Z"

var offset = '+5';  // e.g. if the timeZone is -5

var MyDateWithOffset = new Date( myDate.toGMTString() + offset );   

console.log('MyDateWithOffset:', MyDateWithOffset); // myDateWithOffset: "2018-04-03T20:09:38.000Z"


-1

timezone-js 패키지를 사용했습니다.

var timezoneJS  = require('timezone-js');
var tzdata = require('tzdata');

createDate(dateObj) {
    if ( dateObj == null ) {
        return null;
    }
    var nativeTimezoneOffset = new Date().getTimezoneOffset();
    var offset = this.getTimeZoneOffset();

    // use the native Date object if the timezone matches
    if ( offset == -1 * nativeTimezoneOffset ) {
        return dateObj;
    }

    this.loadTimeZones();

    // FIXME: it would be better if timezoneJS.Date was an instanceof of Date
    //        tried jquery $.extend
    //        added hack to Fiterpickr to look for Dater.getTime instead of "d instanceof Date"
    return new timezoneJS.Date(dateObj,this.getTimeZoneName());
},

-11

이것은 최고의 솔루션입니다

사용 :

// TO ALL dates
Date.timezoneOffset(-240) // +4 UTC

// Override offset only for THIS date
new Date().timezoneOffset(-180) // +3 UTC

암호:

Date.prototype.timezoneOffset = new Date().getTimezoneOffset();

Date.setTimezoneOffset = function(timezoneOffset) {
  return this.prototype.timezoneOffset = timezoneOffset;
};

Date.getTimezoneOffset = function() {
  return this.prototype.timezoneOffset;
};

Date.prototype.setTimezoneOffset = function(timezoneOffset) {
  return this.timezoneOffset = timezoneOffset;
};

Date.prototype.getTimezoneOffset = function() {
  return this.timezoneOffset;
};

Date.prototype.toString = function() {
  var offsetDate, offsetTime;
  offsetTime = this.timezoneOffset * 60 * 1000;
  offsetDate = new Date(this.getTime() - offsetTime);
  return offsetDate.toUTCString();
};

['Milliseconds', 'Seconds', 'Minutes', 'Hours', 'Date', 'Month', 'FullYear', 'Year', 'Day'].forEach((function(_this) {
  return function(key) {
    Date.prototype["get" + key] = function() {
      var offsetDate, offsetTime;
      offsetTime = this.timezoneOffset * 60 * 1000;
      offsetDate = new Date(this.getTime() - offsetTime);
      return offsetDate["getUTC" + key]();
    };
    return Date.prototype["set" + key] = function(value) {
      var offsetDate, offsetTime, time;
      offsetTime = this.timezoneOffset * 60 * 1000;
      offsetDate = new Date(this.getTime() - offsetTime);
      offsetDate["setUTC" + key](value);
      time = offsetDate.getTime() + offsetTime;
      this.setTime(time);
      return time;
    };
  };
})(this));

커피 버전 :

Date.prototype.timezoneOffset = new Date().getTimezoneOffset()


Date.setTimezoneOffset = (timezoneOffset)->
    return @prototype.timezoneOffset = timezoneOffset


Date.getTimezoneOffset = ->
    return @prototype.timezoneOffset


Date.prototype.setTimezoneOffset = (timezoneOffset)->
    return @timezoneOffset = timezoneOffset


Date.prototype.getTimezoneOffset = ->
    return @timezoneOffset


Date.prototype.toString = ->
    offsetTime = @timezoneOffset * 60 * 1000
    offsetDate = new Date(@getTime() - offsetTime)
    return offsetDate.toUTCString()


[
    'Milliseconds', 'Seconds', 'Minutes', 'Hours',
    'Date', 'Month', 'FullYear', 'Year', 'Day'
]
.forEach (key)=>
    Date.prototype["get#{key}"] = ->
        offsetTime = @timezoneOffset * 60 * 1000
        offsetDate = new Date(@getTime() - offsetTime)
        return offsetDate["getUTC#{key}"]()

    Date.prototype["set#{key}"] = (value)->
        offsetTime = @timezoneOffset * 60 * 1000
        offsetDate = new Date(@getTime() - offsetTime)
        offsetDate["setUTC#{key}"](value)
        time = offsetDate.getTime() + offsetTime
        @setTime(time)
        return time

2
와, 나도 마음에 들지 않지만 사람들 이 내장 프로토 타입을 무시하는 것을 정말로 싫어한다고 생각합니다 !
— Qaribou에서 Josh
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.