programing

javascript Date를 문자열화하고 시간대를 유지하는 방법

mailnote 2023. 3. 17. 21:47
반응형

javascript Date를 문자열화하고 시간대를 유지하는 방법

사용자가 작성한 날짜 오브젝트가 있으며 브라우저에 의해 시간대가 입력되어 다음과 같이 표시됩니다.

var date = new Date(2011, 05, 07, 04, 0, 0);
> Tue Jun 07 2011 04:00:00 GMT+1000 (E. Australia Standard Time)

하지만 스트링화하면 타임존은 잘 가버린다.

JSON.stringify(date);
> "2011-06-06T18:00:00.000Z"

브라우저의 타임존을 유지하면서 ISO8601 문자열을 얻는 가장 좋은 방법은 moment.js를 사용하여moment.format()단, 명령어 전체를 serialize 하는 경우는 물론 동작하지 않습니다.JSON.stringify내부(이 경우 Angular)JS)

var command = { time: date, contents: 'foo' };
$http.post('/Notes/Add', command);

완전성을 위해 내 도메인에는 로컬 시간과 오프셋이 모두 필요합니다.

어떤 종류의 오브젝트가 있다고 가정하면Date:

var o = { d : new Date() };

재지정할 수 있습니다.toJSON의 기능Date프로토타입입니다.여기에서는 moment.js를 사용해서moment날짜에서 목적어를 사용한 다음 모멘트의 사용format파라미터 없이 기능하며 오프셋을 포함한 ISO8601 확장 형식을 방출합니다.

Date.prototype.toJSON = function(){ return moment(this).format(); }

개체를 직렬화할 때 요청한 날짜 형식이 사용됩니다.

var json = JSON.stringify(o);  //  '{"d":"2015-06-28T13:51:13-07:00"}'

물론, 그것은 모든 사람에게 영향을 미칠 것이다. Date물건들.특정 날짜 객체의 동작만 변경하려면 해당 특정 객체의 동작만 재정의할 수 있습니다.toJSON다음과 같이 기능합니다.

o.d.toJSON = function(){ return moment(this).format(); }

날짜 등 시스템 객체의 프로토타입에 포함된 기능을 항상 망치지 않으려고 합니다. 나중에 코드 내에서 예기치 않은 방식으로 문제가 발생할 수도 있습니다.

대신 JSON.stringify 메서드는 '문자열화'를 실행하는 방법의 내부를 덮어쓸 수 있는 '문자열화' 함수(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter)를 사용할 수 있습니다.이러한 작업을 수행할 수 있습니다.

var replacer = function(key, value) {

   if (this[key] instanceof Date) {
      return this[key].toUTCString();
   }
   
   return value;
}

console.log(JSON.stringify(new Date(), replacer));
console.log(JSON.stringify({ myProperty: new Date()}, replacer));
console.log(JSON.stringify({ myProperty: new Date(), notADate: "I'm really not", trueOrFalse: true}, replacer));

맷 존슨의 답변을 바탕으로, 저는 이 문제를toJSON의지할 필요 없이moment(그것은 훌륭한 도서관이라고 생각합니다만, 다음과 같은 낮은 레벨의 방법에 의존합니다.toJSON귀찮다)

Date.prototype.toJSON = function () {
  var timezoneOffsetInHours = -(this.getTimezoneOffset() / 60); //UTC minus local time
  var sign = timezoneOffsetInHours >= 0 ? '+' : '-';
  var leadingZero = (Math.abs(timezoneOffsetInHours) < 10) ? '0' : '';

  //It's a bit unfortunate that we need to construct a new Date instance 
  //(we don't want _this_ Date instance to be modified)
  var correctedDate = new Date(this.getFullYear(), this.getMonth(), 
      this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds(), 
      this.getMilliseconds());
  correctedDate.setHours(this.getHours() + timezoneOffsetInHours);
  var iso = correctedDate.toISOString().replace('Z', '');

  return iso + sign + leadingZero + Math.abs(timezoneOffsetInHours).toString() + ':00';
}

setHours메소드는 제공된 값이 "수정"될 때 날짜 객체의 다른 부분을 조정합니다.MDN에서:

지정한 파라미터가 예상 범위를 벗어나면 setHours()는 이에 따라 Date 객체의 날짜 정보를 갱신하려고 합니다.예를 들어 secondsValue에 100을 사용하면 분수가 1(minutesValue + 1)씩 증가하고 초 동안 40이 사용됩니다.

하지만 스트링화하면 타임존은 잘 가버린다.

그 이유는Tue Jun 07 2011 04:00:00 GMT+1000 (E. Australia Standard Time)라고 할 수 있습니다.toString의 of의 Date 「」는stringify '이렇게 하다'라고 것 요.toISOString대신 메서드를 사용합니다.

만약에 '만약에'가toString원하는 형식은 다음과 같습니다.

JSON.stringify(date.toString());

또는 나중에 "명령어"를 문자열화하고 싶기 때문에 처음에 이 값을 입력합니다.

var command = { time: date.toString(), contents: 'foo' };

날짜 시간대를 하기 위해 JS 날짜 개체를 .toLocaleDateString()Date 오브젝트의 포맷을 가능한 모든 방법으로 지원하는 매우 강력한 도우미 기능입니다.

예를 들어 "2019년 2월 1일 금요일, 태평양 표준시"를 인쇄하려는 경우,

 const formatDate = (dateObject : Date) => {
    const options: any  = {
        weekday: 'long',
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        timeZoneName: 'long'
      };
      
    return dateObject.toLocaleDateString('en-CA', options);
  };

「 」, 「 」를으로써,options객체, 날짜 객체에 대해 다양한 형식의 형식을 사용할 수 있습니다.

포맷 방법에 대한 자세한 내용은 다음 매체 문서를 참조하십시오. https://medium.com/swlh/use-tolocaledatestring-to-format-javascript-dates-2959108ea020

date = new Date(JSON.parse(JSON.stringify(new Date(2011, 05, 07, 04, 0, 0))));

에 이어 JSON.stringify. 수 있게 Date.prototype.toJSON★★★★★★ 。

npm:https://www.npmjs.com/package/lbdate

예:

lbDate().init();

const myObj = {
  date: new Date(),
};

const myStringObj = JSON.stringify(myObj);

console.log(myStringObj);

// {"date":"2020-04-01T03:00:00.000+03:00"}

라이브러리는 필요에 따라 일련화 결과를 사용자 정의할 수 있는 옵션도 제공합니다.

언급URL : https://stackoverflow.com/questions/31096130/how-to-json-stringify-a-javascript-date-and-preserve-timezone

반응형