문자열 표현을 사용하지 않고 설정된 표준 시간대로 날짜 만들기
월세 개의 웹 . JavaScript를 하는 Date
번호를 따는 컨스트럭터, 그리고 나서 나는 그 컨스트럭터를 얻습니다.Date
「 」의 「 」의 「 」
new Date(xiYear, xiMonth, xiDate)
올바른 날짜를 지정합니다만, 서머타임이 원인으로, 그 날짜는 GMT+01:00로 간주됩니다.
가 되는 것은 제가 이 시험을 입니다.Date
Ajax 메서드로 전환하여 서버에서 날짜를 역직렬화하면 GMT로 변환되어 하루를 1시간씩 되돌립니다.이제 일, 월, 년을 개별적으로 Ajax 방법으로 넘길 수 있지만, 더 나은 방법이 있을 것 같습니다.
은 나에게 해 주었지만, '어느 쪽인가'를 한 것이다.setUTCHours()
변경 변경: 변경:
Apr 5th 00:00 GMT+01:00
로.
Apr 4th 23:00 GMT+01:00
그리고 UTC 날짜, 월, 연도를 설정해야 했습니다.
Apr 5th 01:00 GMT+01:00
내가 원하던 거야
를 사용합니다..setUTCHours()
실제로 UTC 시간으로 날짜를 설정할 수 있으므로 시스템 전체에서 UTC 시간을 사용할 수 있습니다.
단, date-string을 지정하지 않으면 컨스트럭터에서 UTC를 사용하여 설정할 수 없습니다.
「」를 사용합니다.new Date(Date.UTC(year, month, day, hour, minute, second))
UTC 날짜 객체입니다.
var d = new Date(xiYear, xiMonth, xiDate);
d.setTime( d.getTime() + d.getTimezoneOffset()*60*1000 );
이 답변은 원래 질문에 맞춰져 있으며, 반드시 예상한 답변을 제공하지는 않습니다.특히 일부 사용자는 타임존 오프셋을 추가하는 대신 빼기를 원할 수 있습니다.단, 이 솔루션의 요점은 특정 역직렬화를 위해 javascript의 날짜 객체를 해킹하는 것입니다.모든 경우에 올바른 것은 아닙니다.
시간대를 설정하고 그에 따라 돌아가기만 하면 됩니다.
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'
];
createDateAs가 필요하다고 생각합니다.UTC 함수(convertDateTo와 비교해주세요)UTC)
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());
}
이것은 불가능하다고 생각합니다.Date 객체가 생성된 후에는 타임존을 설정할 수 없습니다.
개념적으로 (실장하고 있지 않은 경우) http://en.wikipedia.org/wiki/Unix_timestamp에 따라 (내 것을 참조:
UNIX 시간(POSIX 시간)은 1970년 1월 1일 목요일 자정 Coordinated Universal Time(UTC; 세계 표준시) 이후 경과한 초수로 정의되는 시간(초)을 나타내는 시스템입니다.
한 번 구성하면 "실시간"의 특정 지점을 나타냅니다.타임존은 추상시점을 사람이 읽을 수 있는 문자열로 변환하려는 경우에만 관련됩니다.
따라서 생성자에서 날짜를 나타내는 실제 시간만 변경할 수 있습니다.시간대를 것 같습니다. 콜 컨스트럭터는, 「로, 「로컬」타임 변수를 .따라서, 이러한 변수를 사용할 수 있는 방법은 없습니다.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');
}
오래된 건 알지만 도움이 된다면 모멘트 타임존을 사용할 수 있을 거예요.못 보셨다면 한번 보세요.
두 개의 편리한 시간 조작 라이브러리입니다.
시간대를 포함한 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 '로케일'이라는 로케일을 알 수 있으며 로컬로 기본 설정되지 않음), 지정된 표준 시간대를 수동으로 적용합니다.
누군가 실제로 Javascript 날짜 오브젝트에 대해 5분 이상 생각해 봤더라면 좋았을 텐데...
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 시간 오프셋 목록
getTimeZoneOffset은 UTC + z에서 마이너스입니다.
var d = new Date(xiYear, xiMonth, xiDate);
if(d.getTimezoneOffset() > 0){
d.setTime( d.getTime() + d.getTimezoneOffset()*60*1000 );
}
다른 사용자가 UTC를 새 컨스트럭터에게 전달한 말미에 배치하는 것이 도움이 될 수 있습니다.
에서는 at어크크 at at at at at at at at 라고 말할 수 있다.var date = new Date("2014-01-01 11:00:00 UTC")
// 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)
단일 라인 솔루션
new Date(new Date(1422524805305).getTime() - 330*60*1000)
1422524805305 대신 밀리초 단위의 타임스탬프를 사용합니다.330 대신 분 단위 시간대 오프셋을 사용합니다. GMT(예: 인도 +5:30은 5*60+30 = 330분)
정확한 날짜를 알 수 있는 가장 쉬운 방법은 datejs를 사용하는 것입니다.
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 GMT-0500 (동부 표준시)
2016년 1월 12일 (화) 00:00:00 GMT-0500 (동부 표준시)
https://jsfiddle.net/vp1ena7b/3/
'add Minutes'는 datesjs에서 유래한 것으로, 당신은 아마 이것을 혼자서 순수 js로 할 수 있을 것입니다만, 저는 이미 프로젝트에 datesjs가 있었기 때문에, 그것을 사용하여 올바른 날짜를 얻을 수 있는 방법을 찾았습니다.
이게 누군가에게 도움이 될 것 같아서...
이 코드는 브라우저 시간대로 포맷된 날짜 개체를 반환합니다.
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;
}
다음은 날짜 개체를 얻기 위해 사용할 수 있는 함수입니다.
const getUTCDate = (date) => {
const d = new Date(date);
const utcDate = new Date(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate());
return utcDate;
}
const string = '1930-08-12T00:00:00.000000Z';
const utcDate = getUTCDate(string);
// returns Tue Aug 12 1930 00:00:00 GMT-0800 (Pacific Daylight Time)
에 있어서의 마일리지
var d = new Date(xiYear, xiMonth, xiDate).toLocaleString();
달력 보기에도 비슷한 문제가 있었어요.제 연구는 추가 라이브러리나 하드 코드화된 멀티플라이어 없이 매우 간단한 해결책으로 이어졌습니다.
주요 정보:
- ISO 자바스크립트날짜 유틸리티가 해당 형식의 날짜 값을 반환할 가능성이 높다고 가정합니다.
내 달력 선택기는 날짜를 현지화된 형식으로 표시합니다: mm/dd/yyyy
단, ISO 형식의 날짜 값은 yyy-mm-dd로 반환됩니다.
//Select "08/12/2020" in Date Picker date_input var input = $('#date_input').val(); //input: 2020-08-12
- Date.getTimezoneOffset()은 오프셋을 분 단위로 반환합니다.
예:
문자열 형식을 변경하지 않고 기본 반환 날짜 값을 사용하면 날짜가 시간대로 설정되지 않을 수 있습니다.이로 인해 예기치 않은 결과가 발생할 수 있습니다.
var input = $('#date_input').val(); //input: 2020-08-12
var date = new Date(input); //This get interpreted as an ISO date, already in UTC
//date: Tue Aug 11 2020 20:00:00 GMT-0400 (Eastern Daylight Time)
//date.toUTCString(): Wed, 12 Aug 2020 00:00:00 GMT
//date.toLocaleDateString('en-US'): 8/11/2020
ISO 표준 yyy-mm-dd와 다른 날짜 문자열 형식을 사용하면 표준 시간대가 날짜에 적용됩니다.
var date = new Date("08/12/2020"); //This gets interpreted as local timezone
//date: Wed Aug 12 2020 00:00:00 GMT-0400 (Eastern Daylight Time)
//date.toUTCString(): Wed, 12 Aug 2020 04:00:00 GMT
//date.toLocaleDateString('en-US'): 8/12/2020
솔루션:
에 구애받지 않는 하려면 , 「타임존」을 합니다.Date.getTimezoneOffset()
이치노이것은 원래 날짜 문자열 형식(UTC 날짜 또는 현지화된 날짜) 중 하나로 작동합니다.일관된 결과를 제공하므로 UTC로 정확하게 변환하여 저장하거나 다른 코드와 상호 작용할 수 있습니다.
var input = $('#date_input').val();
var date = new Date(input);
date.setMinutes(date.getMinutes() + date.getTimezoneOffset());
//date: Wed Aug 12 2020 00:00:00 GMT-0400 (Eastern Daylight Time)
//date.toUTCString(): Wed, 12 Aug 2020 04:00:00 GMT
//date.toLocaleDateString('en-US'): 8/12/2020
const date = new Date("2020-12-16 17:45:00 UTC");
정상적으로 동작합니다.
여기서 본 최고의 솔루션은
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>
날짜 개체를 만들 때:
new Date(year, month, day, hour, minute)
로컬 호스트에서는 잘 하고 있습니다.서버에 전개하면 서버가 다른 타임존에 있기 때문에 서버가 파손됩니다.
get Timezone Offset()을 사용할 수 없습니다.여름/겨울 시간에 따라 집의 시간대 오프셋이 필요합니다.
// add diff minutes between myself (HOME) and server
timezoneHomeOffset (d, tz = 'Europe/Copenhagen') {
const utc = new Date(d.getTime())
const dHome = new Date(d.toLocaleString('en-US', { timeZone: tz }))
const diff = Math.round((utc - dHome) / 60000) // 60*1000 => minutes
d.setMinutes(d.getMinutes() + diff)
return d
}
라이브러리를 사용하여 표준 시간대를 변경할 수 있습니다.
moment-timezone
var moment = require("moment-timezone");
const today = new Date();
var timeGet = moment(today);
timeGet.tz("Asia/Karachi").format("ha z");
지역 시간대를 변경하여 지역 영역을 붙여넣고 실제 gmt+ 문제를 해결할 수 있습니다.
상세한 것에 대하여는, 모멘트 타임 존 공식 문서를 참조해 주세요.
사실 그렇게 어려운 일은 아니지만, 해결책을 마련하는 것은 분명 직관적이지 않습니다.여기에는 정말 난해한 답변이 몇 가지 있다.도입하고 있는 서버의 타임 존에 관계없이, 서버의 타임 스탬프가 로컬의 타임 스탬프와 일치하고 있는 것을 확인하기 위해서, 다음과 같이 생각해 냈습니다.
(CET = 중앙유럽 표준시입니다.이것은 우연히도 제 개인적인 표준시입니다.어느 특정 표준시의 오프셋을 취득해, 계산해, 필요에 따라서 인수로 할 수도 있습니다만, 제 목적을 위해서, 제 날짜를 모두 하나의 일관된 표준시로 하는 것이 필요했습니다.)
const convertDateToCET = function(date) {
date = new Date(date)
// let startTime = date.getTime();
const cetOffset = -120; // this is the number you get from running
// `(new Date()).getTimezoneOffset()` if you're on a machine in CET
const offsetFromCET = (date.getTimezoneOffset() - cetOffset);
const cetMillsecondOffset = ( cetOffset* 60 * 1000);
date = new Date( date.getTime() - cetMillsecondOffset )
// let endTime = date.getTime()
// console.log("updated date from",startTime,"to",endTime)
return date;
},
이를 사용하여 예상대로 시간을 만들 수 있습니다. 예를 들어,
let myDate = new Date("12-4-2021")
myDate.setHour(14)
myDate.setMinute(30)
// now myDate is 2:30pm, December 4th, 2021, in whatever the timezone the machine of code running happens to be in
myDate = convertDateToCET(myDate)
// now myDate will show up as 2:30pm, Dec 4th, 2021, mapped into your local timezone
// so, if you're in the UK, and one hour behind CET, myDate is now 1:30pm, Dec 4th, 2021
서의 열쇠는 ★★★★★★★★★★★★★★★★★★★★★★★★」date.getTimezoneOffset()
, 그 는 「CET」, 「CET」가 -120
그 결과 CET는 소거되어 차이가 없습니다(따라서 CET는 CET 출력으로 이어집니다).CET보다 됩니다.-60
즉,-60 + 120 = +60
그 결과 입력 시간이 1시간 변경되는 등 계속됩니다.
이런 경우에는 모든 것을 변환하고 UTC 내의 모든 것을 사용하는 것이 더 합리적일 수 있지만, 입력 시간은 모두 CET에 있으며, 원래 머신상의 로컬 상태를 기반으로 시스템을 개발했기 때문에 이 유틸리티를 사용하여 몇 가지 중요한 장소에서 호출을 하는 것만으로 기존 코드를 변환할 수 있었습니다.
주의:이 함수 호출을 같은 날짜에 여러 번 적용하지 마십시오. 오프셋을 여러 번 적용하면 꺼지므로!
이것은, 다른 시간대(IST, PST, 멕시코, 중앙 아메리카):
let dateUtc: any = new Date(Date.parse(data.details.dateOfBirth));
dateUtc = new Date(dateUtc.getTime() + Math.abs(dateUtc.getTimezoneOffset()*60000));
console.log(dateUtc);
두 날짜 사이의 시간 차이를 확인하려면 첫 번째 원하는 시간대에서 두 번째 시간대가 작거나 큰지 확인하고 시간을 빼거나 더하면 됩니다.
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));
}
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
내 뇌의 통증.WORDPRESS를 사용하여 서버에서 js로 현재와 같은 시간대를 가져오는 방법.
var dnow = new Date();
dnow = dnow.getTime() + dnow.getTimezoneOffset()*60*1000 + <?= get_option( 'gmt_offset' ) ?> * 60*60*1000;
우선 현재 날짜를 알아야 합니다.그런 다음 사용자 시간대 오프셋을 제거해야 합니다.그런 다음 WordPress 옵션 페이지에서 gmt 오프셋을 추가합니다.
이건 나한테 효과가 있었어.하지만 그것이 좋은 생각인지는 확실하지 않다.
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"
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());
},
이것이 최선책입니다.
사용방법:
// 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
언급URL : https://stackoverflow.com/questions/439630/create-a-date-with-a-set-timezone-without-using-a-string-representation
'itsource' 카테고리의 다른 글
PHP에서 동적 변수 이름에 중괄호 사용 (0) | 2023.02.06 |
---|---|
PHP(라인 피드)에 파일에 새 줄 쓰기 (0) | 2023.02.06 |
array_module 및 키 번호 변경 (0) | 2023.02.06 |
[]를 사용하여 값을 추가하기 전에 PHP 어레이를 선언해야 합니까? (0) | 2023.02.06 |
오류 - npm - node.js를 사용하여 mariasql 패키지를 설치하는 중 (0) | 2023.02.06 |