your programing

"올바른"JSON 날짜 형식

lovepro 2020. 9. 27. 13:35
반응형

"올바른"JSON 날짜 형식


JSON 날짜 형식에 대한 여러 가지 표준을 보았습니다.

"\"\\/Date(1335205592410)\\/\""         .NET JavaScriptSerializer
"\"\\/Date(1335205592410-0500)\\/\""    .NET DataContractJsonSerializer
"2012-04-23T18:25:43.511Z"              JavaScript built-in JSON object
"2012-04-21T18:25:43-05:00"             ISO 8601

어느 것이 맞습니까? 아니면 최고? 이것에 대한 어떤 종류의 표준이 있습니까?


JSON 자체 날짜 표시 방법을 지정하지 않지만 JavaScript는 지정합니다.

당신은 해야한다 에 의해 방출되는 형식을 사용 DatetoJSON방법 :

2012-04-23T18:25:43.511Z

그 이유는 다음과 같습니다.

  1. 사람이 읽을 수 있지만 간결합니다.

  2. 올바르게 정렬됩니다.

  3. 연대기를 다시 설정하는 데 도움이 될 수있는 분수 초를 포함합니다.

  4. ISO 8601을 준수합니다.

  5. ISO 8601은 10 년 이상 국제적으로 확립되었습니다.

  6. ISO 8601은 W3C , RFC3339XKCD 에서 보증합니다.

, 지금까지 작성된 모든 날짜 라이브러리는 "1970 년 이후 밀리 초"를 이해할 수 있습니다. 따라서 쉬운 이식성을 위해 ThiefMaster 가 옳습니다.


JSON은 날짜에 대해 아무것도 모릅니다. .NET이하는 일은 비표준 해킹 / 확장입니다.

DateJavaScript에서 객체 로 쉽게 변환 할 수있는 형식 , 즉 new Date(...). 가장 쉽고 가장 이식 가능한 형식은 1970 년 이후의 밀리 초를 포함하는 타임 스탬프입니다.


올바른 형식이 없습니다 . JSON 사양은 그것을 할 너무 많은 다른 방법이 왜 날짜를 교환하는 형식을 지정하지 않습니다.

가장 좋은 형식은 틀림없이 ISO 8601 형식으로 표현 된 날짜 입니다 ( Wikipedia 참조 ). 잘 알려져 있고 널리 사용되는 형식이며 다양한 언어로 처리 할 수 ​​있으므로 상호 운용성에 매우 적합합니다. 예를 들어 생성 된 json을 제어 할 수있는 경우 json 형식으로 다른 시스템에 데이터를 제공 할 경우 날짜 교환 형식으로 8601을 선택하는 것이 좋습니다.

생성 된 json을 제어 할 수없는 경우 (예 : 여러 기존 시스템의 json 소비자 인 경우)이를 처리하는 가장 좋은 방법은 예상되는 다른 형식을 처리하는 날짜 구문 분석 유틸리티 함수를 사용하는 것입니다.


에서 RFC 7493합니다 (I-JSON 메시지 형식) :

I-JSON은 요청하는 사람에 따라 Internet JSON 또는 Interoperable JSON을 나타냅니다.

프로토콜에는 종종 타임 스탬프 또는 기간을 포함하도록 설계된 데이터 항목이 포함됩니다. 이러한 모든 데이터 항목은 RFC 3339에 지정된대로 ISO 8601 형식의 문자열 값으로 표현 하는 것이 좋습니다. 추가 제한은 소문자가 아닌 대문자를 사용하고 시간대가 기본으로 포함되지 않으며 선택적 후행 초입니다. 값이 "00"인 경우에도 포함됩니다. 또한 기간이 포함 된 모든 데이터 항목은 RFC 3339의 부록 A에있는 "기간"생성을 준수하고 동일한 추가 제한 사항을 적용하는 것이 좋습니다.


참고로이 형식이 사용되는 것을 보았습니다.

Date.UTC(2017,2,22)

함수에서 지원하는 JSONP 와 함께 작동 $.getJSON()합니다. 내가이 접근 방식을 추천 할만큼 멀리 갈지 모르겠습니다. 사람들이 이런 식으로하고 있기 때문에 가능성으로 던져 버릴뿐입니다.

FWIW : 통신 프로토콜에서 epoch 이후 초를 사용하지 마십시오. 또는 epoch 이후 밀리 초를 사용하지 마십시오 . 윤초를 무작위로 구현했기 때문에 위험하기 때문입니다 (발신자와 수신자가 모두 UTC 윤초를 올바르게 구현하는지 알 수 없습니다).

일종의 애완 동물은 싫어하지만 많은 사람들은 UTC가 GMT의 새로운 이름 일 뿐이라고 생각합니다. 시스템이 윤초를 구현하지 않으면 GMT를 사용하는 것입니다 (잘못된 경우에도 종종 UTC라고 함). 윤초를 완전히 구현하면 실제로 UTC를 사용하는 것입니다. 미래의 윤초는 알 수 없습니다. 필요한 경우 IERS에 의해 게시되며 지속적인 업데이트가 필요합니다. 윤초를 구현하려고 시도하지만 오래된 참조 테이블 (생각하는 것보다 더 일반적)을 포함하고있는 시스템을 실행하고 있다면 GMT도 UTC도없고 UTC 인 것처럼 가장 불안정한 시스템을 갖게됩니다.

이러한 날짜 카운터는 세분화 된 형식 (y, m, d 등)으로 표현 된 경우에만 호환됩니다. epoch 형식에서는 절대 호환되지 않습니다. 명심하십시오.


JSON 자체에는 날짜 형식이 없으며 누군가가 날짜를 저장하는 방법은 중요하지 않습니다. 그러나이 질문에는 javascript로 태그가 지정되었으므로 JSON에 javascript 날짜를 저장하는 방법을 알고 싶다고 가정합니다. JSON.stringify메서드에 날짜를 전달할 수 있으며 Date.prototype.toJSON기본적으로 사용되며 차례로 Date.prototype.toISOString( Date.toJSON의 MDN )을 사용합니다.

const json = JSON.stringify(new Date());
const parsed = JSON.parse(json); //2015-10-26T07:46:36.611Z
const date = new Date(parsed); // Back to date object

나는 또한 유용 사용하는 발견 reviver의 매개 변수 JSON.parse( JSON.parse에 MDN을 내가 JSON 문자열을 읽을 때마다 자동으로 자바 스크립트 날짜에 ISO 문자열을 다시 변환).

const isoDatePattern = new RegExp(/\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/);

const obj = {
 a: 'foo',
 b: new Date(1500000000000) // Fri Jul 14 2017, etc...
}
const json = JSON.stringify(obj);

// Convert back, use reviver function:
const parsed = JSON.parse(json, (key, value) => {
    if (typeof value === 'string' &&  value.match(isoDatePattern)){
        return new Date(value); // isostring, so cast to js date
    }
    return value; // leave any other value as-is
});
console.log(parsed.b); // // Fri Jul 14 2017, etc...

범용 상호 운용성을 위한 최상의 형식 은 ISO-8601 문자열이 아니라 EJSON에서 사용하는 형식이라고 생각합니다.

{ "myDateField": { "$date" : <ms-since-epoch> } }

여기에 설명 된대로 : https://docs.meteor.com/api/ejson.html

혜택

  1. Parsing performance: If you store dates as ISO-8601 strings, this is great if you are expecting a date value under that particular field, but if you have a system which must determine value types without context, you're parsing every string for a date format.
  2. No Need for Date Validation: You need not worry about validation and verification of the date. Even if a string matches ISO-8601 format, it may not be a real date; this can never happen with an EJSON date.
  3. Unambiguous Type Declaration: as far as generic data systems go, if you wanted to store an ISO string as a string in one case, and a real system date in another, generic systems adopting the ISO-8601 string format will not allow this, mechanically (without escape tricks or similar awful solutions).

Conclusion

I understand that a human-readable format (ISO-8601 string) is helpful and more convenient for 80% of use cases, and indeed no-one should ever be told not to store their dates as ISO-8601 strings if that's what their applications understand, but for a universally accepted transport format which should guarantee certain values to for sure be dates, how can we allow for ambiguity and need for so much validation?


When in doubt simply go to the javascript web console of a modern browser by pressing F12 (Ctrl+K in Firefox) and write the following:

new Date().toISOString()

Will output:

"2019-07-04T13:33:03.969Z"

Ta-da!!


In Sharepoint 2013, getting data in JSON there is no format to convert date into date only format, because in that date should be in ISO format

yourDate.substring(0,10)

This may be helpful for you


The prefered way is using 2018-04-23T18:25:43.511Z...

The picture below shows why this is the prefered way:

JSON 날짜

So as you see Date has a native Method toJSON, which return in this format and can be easily converted to Date again...


var myDateFormate = DateConvert(YourDate); //output ex : 01-Jan-2019

function DateConvert(data) {
    var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    var data1 = data.replace("/Date(", "").replace(")/", "");
    var date = new Date(parseInt(data1));
    var month = date.getMonth();// + 1;
    return date.getDate() + "-" + (month.length > 1 ? month : monthNames[month]) + "-" + date.getFullYear();
}

it is work for me with parse Server

{
    "ContractID": "203-17-DC0101-00003-10011",
    "Supplier":"Sample Co., Ltd",
    "Value":12345.80,
    "Curency":"USD",
    "StartDate": {
                "__type": "Date",
                "iso": "2017-08-22T06:11:00.000Z"
            }
}

There is only one correct answer to this and most systems get it wrong. Number of milliseconds since epoch, aka a 64 bit integer. Time Zone is a UI concern and has no business in the app layer or db layer. Why does your db care what time zone something is, when you know it's going to store it as a 64 bit integer then do the transformation calculations.

Strip out the extraneous bits and just treat dates as numbers up to the UI. You can use simple arithmetic operators to do queries and logic.


The following code has worked for me. This code will print date in DD-MM-YYYY format.

DateValue=DateValue.substring(6,8)+"-"+DateValue.substring(4,6)+"-"+DateValue.substring(0,4);

else, you can also use:

DateValue=DateValue.substring(0,4)+"-"+DateValue.substring(4,6)+"-"+DateValue.substring(6,8);

I think that really depends on the use case. In many cases it might be more beneficial to use a proper object model (instead of rendering the date to a string), like so:

{
"person" :
      {
 "name" : {
   "first": "Tom",
   "middle": "M",
  ...
}
 "dob" :  {
         "year": 2012,
         "month": 4,
         "day": 23,
         "hour": 18,
         "minute": 25,
         "second": 43,
         "timeZone": "America/New_York"
    }   
   }
}

Admittedly this is more verbose than RFC 3339 but:

  • it's human readable as well
  • it implements a proper object model (as in OOP, as far as JSON permits it)
  • it supports time zones (not just the UTC offset at the given date and time)
  • it can support smaller units like milliseconds, nanoseconds, ... or simply fractional seconds
  • 별도의 구문 분석 단계 (날짜-시간 문자열 구문 분석)가 필요하지 않으며 JSON 구문 분석기가 모든 작업을 수행합니다.
  • 날짜-시간 프레임 워크 또는 모든 언어로 구현하여 쉽게 생성
  • 다른 달력 스케일 (히브리어, 중국어, 이슬람 ...) 및 시대 (AD, BC, ...)를 지원하도록 쉽게 확장 할 수 있습니다.
  • 10000 년 안전합니다 ;-) (RFC 3339는 아닙니다)
  • 하루 종일 날짜 및 부동 시간 지원 (Javascript는 지원 Date.toJSON()하지 않음)

올바른 정렬 (RFC 3339에 대한 funroll에서 언급 한대로)이 날짜를 JSON으로 직렬화 할 때 실제로 필요한 기능이라고 생각하지 않습니다. 또한 시간대 오프셋이 동일한 날짜 시간에만 해당됩니다.

참고 URL : https://stackoverflow.com/questions/10286204/the-right-json-date-format

반응형