JSON Stringify가 UTC로 인해 날짜를 변경합니다.
JavaScript의 날짜 객체는 위치 때문에 항상 UTC +2로 표시됩니다.그래서 이렇게
Mon Sep 28 10:00:00 UTC+0200 2009
문제는, 을 실행하는 것입니다.JSON.stringify
를 to converts converts converts converts로 합니다.
2009-09-28T08:00:00Z (notice 2 hours missing i.e. 8 instead of 10)
내가 원하는 것은 날짜와 시간이 존중되는 것이다 하지만 그것은 아니다, 그래서 그것은 그래야 한다.
2009-09-28T10:00:00Z (this is how it should be)
기본적으로 다음과 같이 사용합니다.
var jsonData = JSON.stringify(jsonObject);
replacer 파라미터(stringify의 두 번째 파라미터)를 전달하려고 했지만 문제는 값이 이미 처리되었다는 것입니다.
도 ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★toString()
★★★★★★★★★★★★★★★★★」toUTCString()
하지만 이것들도 내가 원하는 걸 주진 않아
누가 나를 도와줄 수 있나요?
나는 최근에 같은 문제에 부딪혔다.그리고 다음 코드를 사용하여 해결했습니다.
x = new Date();
let hoursDiff = x.getHours() - x.getTimezoneOffset() / 60;
let minutesDiff = (x.getHours() - x.getTimezoneOffset()) % 60;
x.setHours(hoursDiff);
x.setMinutes(minutesDiff);
은 JSON을 합니다.Date.prototype.toISOString
현지 시간을 나타내지 않는 함수(UTC 미수정 시간) - 날짜 출력을 보면 UTC+2시간임을 알 수 있습니다.이 때문에 JSON 문자열이 2시간씩 변경되지만 여러 시간대에 걸쳐 동일한 시간을 올바르게 나타낼 수 있습니다.
date.toJSON()은 UTC-Date를 문자열 형식으로 인쇄합니다(따라서 이 값을 JSON 형식으로 변환할 때 오프셋을 추가합니다).
date = new Date();
new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toJSON();
참고로 '2009-09-28'의 마지막 'Z'는T08:00:00Z"는 시간이 실제로 UTC임을 의미합니다.
상세한 것에 대하여는, http://en.wikipedia.org/wiki/ISO_8601 를 참조해 주세요.
사용할 수 있는 으로 강제 사용 가능JSON.stringify
시간대를 무시합니다.
- 순수 자바스크립트(Anatoliy 답변 기준):
// Before: JSON.stringify apply timezone offset
const date = new Date();
let string = JSON.stringify(date);
console.log(string);
// After: JSON.stringify keeps date as-is!
Date.prototype.toJSON = function(){
const hoursDiff = this.getHours() - this.getTimezoneOffset() / 60;
this.setHours(hoursDiff);
return this.toISOString();
};
string = JSON.stringify(date);
console.log(string);
모멘트 + 모멘트 시간대 라이브러리 사용:
const date = new Date();
let string = JSON.stringify(date);
console.log(string);
Date.prototype.toJSON = function(){
return moment(this).format("YYYY-MM-DDTHH:mm:ss:ms");;
};
string = JSON.stringify(date);
console.log(string);
<html>
<header>
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data-10-year-range.min.js"></script>
</header>
</html>
여기 또 다른 답변이 있습니다(개인적으로는 이것이 더 적절하다고 생각합니다).
var currentDate = new Date();
currentDate = JSON.stringify(currentDate);
// Now currentDate is in a different format... oh gosh what do we do...
currentDate = new Date(JSON.parse(currentDate));
// Now currentDate is back to its original form :)
현지 시간으로 포맷할 때 moment.displaces를 사용할 수 있습니다.
Date.prototype.toISOString = function () {
return moment(this).format("YYYY-MM-DDTHH:mm:ss");
};
조금 늦었지만 다음과 같이 프로토타입을 사용하여 날짜의 경우 언제든지 toJson 함수를 덮어쓸 수 있습니다.
Date.prototype.toJSON = function(){
return Util.getDateTimeString(this);
};
이 경우 Util.getDateTimeString(이것)은 다음과 같은 문자열을 반환합니다.2017-01-19T00:00:00Z"
미국 동부 해안에서만 작동하며 UTC에는 날짜를 저장하지 않는 레거시 관련 작업을 하다 보니 모두 EST입니다.브라우저 사용자 입력에 따라 날짜를 필터링해야 하므로 현지 시간으로 JSON 형식으로 날짜를 넘겨야 합니다.
이미 게시된 이 솔루션에 대해 자세히 설명하자면 다음과 같습니다.
// Could be picked by user in date picker - local JS date
date = new Date();
// Create new Date from milliseconds of user input date (date.getTime() returns milliseconds)
// Subtract milliseconds that will be offset by toJSON before calling it
new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toJSON();
따라서 JSON()에 추가되는 시간을 예상하여 시작 날짜에서 시간(밀리초 단위(분 단위)을 뺀다고 알고 있습니다.
JavaScript는 보통 로컬 시간대를 UTC로 변환합니다.
date = new Date();
date.setMinutes(date.getMinutes()-date.getTimezoneOffset())
JSON.stringify(date)
통상, 각 유저의 현지 시간에 날짜를 표시하고 싶다.
GMT(UTC)를 사용하고 있습니다.
Date.parse(jsondatestring)를 사용하여 로컬 시간 문자열을 가져옵니다.
각 방문자에게 현지 시간을 보여주고 싶지 않다면요.
이 경우 아나톨리의 방법을 사용합니다.
를 사용하여 이 문제를 해결했습니다.moment.js
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
var newMinDate = moment(datePicker.selectedDates[0]);
var newMaxDate = moment(datePicker.selectedDates[1]);
// Define the data to ask the server for
var dataToGet = {"ArduinoDeviceIdentifier":"Temperatures",
"StartDate":newMinDate.format('YYYY-MM-DD HH:mm'),
"EndDate":newMaxDate.format('YYYY-MM-DD HH:mm')
};
alert(JSON.stringify(dataToGet));
i i하 i i 。flatpickr.min.js
선택기는 일치하지 않습니다.생성된 JSON 개체의 시간은 제공된 로컬 시간과 일치하지만 달력 선택기는 일치하지 않습니다.
여기 아주 깔끔하고 간단한 것이 있습니다(적어도 그렇다고 생각합니다).클론 작성이나 브라우저의 네이티브 함수 중 toJSON(참조:javascript Date를 문자열화하고 시간대를 유지하는 방법, courty Shawson)
JSON.stringify에 리페이서 함수를 전달하여 마음껏 문자열화!!!이렇게 하면 시간과 분간의 차이나 다른 조작을 할 필요가 없습니다.
중간 결과를 보기 위해 console.logs를 넣었기 때문에 현재 진행 상황과 재귀가 어떻게 작동하는지 알 수 있습니다.여기서 알 수 있는 것은 리페이서에 대한 파라미터 값이 이미 ISO 날짜 형식으로 변환되어 있다는 것입니다.원본 데이터로 작업할 때는 이 키를 사용하십시오.
var replacer = function(key, value)
{
var returnVal = value;
if(this[key] instanceof Date)
{
console.log("replacer called with key - ", key, " value - ", value, this[key]);
returnVal = this[key].toString();
/* Above line does not strictly speaking clone the date as in the cloned object
* it is a string in same format as the original but not a Date object. I tried
* multiple things but was unable to cause a Date object being created in the
* clone.
* Please Heeeeelp someone here!
returnVal = new Date(JSON.parse(JSON.stringify(this[key]))); //OR
returnVal = new Date(this[key]); //OR
returnVal = this[key]; //careful, returning original obj so may have potential side effect
*/
}
console.log("returning value: ", returnVal);
/* if undefined is returned, the key is not at all added to the new object(i.e. clone),
* so return null. null !== undefined but both are falsy and can be used as such*/
return this[key] === undefined ? null : returnVal;
};
ab = {prop1: "p1", prop2: [1, "str2", {p1: "p1inner", p2: undefined, p3: null, p4date: new Date()}]};
var abstr = JSON.stringify(ab, replacer);
var abcloned = JSON.parse(abstr);
console.log("ab is: ", ab);
console.log("abcloned is: ", abcloned);
/* abcloned is:
* {
"prop1": "p1",
"prop2": [
1,
"str2",
{
"p1": "p1inner",
"p2": null,
"p3": null,
"p4date": "Tue Jun 11 2019 18:47:50 GMT+0530 (India Standard Time)"
}
]
}
Note p4date is string not Date object but format and timezone are completely preserved.
*/
저도 같은 문제에 부딪혔어요.해결 방법은 다음과 같습니다.
var currentTime = new Date();
Console.log(currentTime); //Return: Wed Sep 15 13:52:09 GMT-05:00 2021
Console.log(JSON.stringify(currentTime)); //Return: "2021-09-15T18:52:09.891Z"
var currentTimeFixed = new Date(currentTime.setHours(currentTime.getHours() - (currentTime.getUTCHours() - currentTime.getHours())));
Console.log(JSON.stringify(currentTimeFixed)); //Return: "2021-09-15T13:52:09.891Z"
서비스 콜을 하는 다음 코드 블로그를 작성했습니다.모든 투고에서 json을 시리얼화하려고 시도하고 다시 로컬 날짜로 포맷합니다.
protected async post(endPoint: string, data, panelName?: string, hasSuccessMessage: boolean = false): Promise<Observable<any>> {
const options = this.InitHeader(true);
const url: string = this._baseUrl + endPoint;
Date.prototype.toJSON = function () {
return moment(this).format("YYYY-MM-DDThh:mm:00.000Z");;
};
return await this._http.post(url, data, options).pipe(map(response => {
return this.Map<any>(response, null);
}));
}
요약하면 서버 백엔드가 타임존에 의존하지 않는지 여부입니다.그렇지 않은 경우 서버의 타임존이 클라이언트와 동일하다고 가정하거나 클라이언트의 타임존에 대한 정보를 전송하여 계산에 포함시켜야 합니다.
우체국SQL 백엔드 기반의 예:
select '2009-09-28T08:00:00Z'::timestamp -> '2009-09-28 08:00:00' (wrong for 10am)
select '2009-09-28T08:00:00Z'::timestamptz -> '2009-09-28 10:00:00+02'
select '2009-09-28T08:00:00Z'::timestamptz::timestamp -> '2009-09-28 10:00:00'
타임존 로직을 적절히 실장하지 않는 경우는, 마지막은 데이타베이스에서 사용하는 것이 될 가능성이 있습니다.
toJSON
, 항상 올바른 날짜와 시간을 제공하는 포맷 기능을 사용할 수 있습니다 +GMT
이것은 가장 견고한 디스플레이 옵션입니다.토큰 문자열을 사용하여 대응하는 값으로 대체합니다.
각도 8로 해봤는데
모델 작성:
export class Model { YourDate: string | Date; }
컴포넌트로
model : Model; model.YourDate = new Date();
API에 저장 날짜 보내기
API에서 데이터를 로드할 때 다음을 수행합니다.
model.YourDate = new Date(model.YourDate+"Z");
당신은 당신의 시간대와 날짜를 정확히 맞출 것입니다.
이 경우 날짜를 UNIX 타임스탬프로 변환해야 합니다.
timestamp = testDate.getTime();
strJson = JSON.stringify(timestamp);
그런 다음 다시 사용하여 날짜 개체를 만들고 형식을 지정할 수 있습니다.javascript를 사용한 예 및toLocaleDateString
( https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Date/toLocaleDateString )
newDateObject = new Date(JSON.parse(strJson));
newDateObject = newDateObject.toLocalDateStrin([
"fr-FR",
]);
stringify를 사용하여 AJAX를 사용하는 경우 유용하지 않습니다.타임스탬프를 전송하여 스크립트에 입력하기만 하면 됩니다.
$newDateObject = new \DateTime();
$newDateObject->setTimestamp(round($timestamp/1000));
주의해 주세요getTime()
시간(밀리초)과 PHP 함수가 반환됩니다.setTimestamp
몇 초 만에 끝납니다.그래서 1000으로 나눠서round
.
Angular에 다음을 배치합니다.index.js
스크립트 섹션:
setTimeout(function (){
Date.prototype.toJSON = function(){
return new Date(this).toLocaleDateString("en-US") + " "+new Date(this).toLocaleTimeString();
}},1000);
언급URL : https://stackoverflow.com/questions/1486476/json-stringify-changes-time-of-date-because-of-utc
'source' 카테고리의 다른 글
mongodb 여러 어레이 항목에서 검색 (0) | 2023.02.14 |
---|---|
Postgres JSON 데이터 유형 Rails 쿼리 (0) | 2023.02.14 |
useState는 동기화되어 있습니까? (0) | 2023.02.14 |
구체화된 뷰와표:어떤 장점이 있습니까? (0) | 2023.02.14 |
웹 팩을 사용하여 angularjs를 Import하기 위한 베스트 프랙티스는 무엇입니까? (0) | 2023.02.10 |