DEV Community

loading...

Date Handling in Angular Application (Part 1 — JSON and JavaScript Date Object Study)

imben1109 profile image Ben Updated on ・2 min read

https://medium.com/self-learning/date-handling-in-angular-application-part-1-json-and-javascript-date-object-s-8f77a69734c7

Introduction

In modern web application, JSON is widely used as communication format between server side and client side. However, JSON do not specify the format of date object.

General Agreement

ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) is a general agreement for exchange format of date object.

JavaScript Date Object

var now = new Date()

The above is a way to create a date object in browser environment.

Time zone and locale dependent

By Default, browser would use the time zone and locale to display date in browser. i.e.

var now = new Date();
console.log(now.toString());

Result: Sun Jun 30 2019 23:18:34 GMT+0800 (China Standard Time)

The some method in the date object in browser are timezone and locate dependent.

var now = new Date();
now.getHours()

result: 23

ISO Format (Time zone and locale independent)

As mention above, ISO Date String Format is a general agreement format in JSON format.

var now = new Date()
console.log(now.toISOString());

result: 2019-06-30T15:55:46.936Z

JSON Conversion

Convert Date Object to JSON

var jsonData = {date1: new Date()};
console.log(JSON.stringify(jsonData));

result: {"date1":"2019-06-30T16:26:18.460Z"}

Revert JSON to JavaScript Object

var jsonData = {date1: new Date()};
var jsonDataStr = JSON.stringify(jsonData)
var revertedJsonData = JSON.parse(jsonDataStr);
console.log(revertedJsonData);

result: {date1: "2019-06-30T16:30:19.096Z"}

It is found the JSON reversion (JSON.parse) do not know the type of Date. It cannot convert the date string to Date object.

The ISO 8601 is a agreed format for the date object json string. We could use the reviver function in JSON.parse to help the conversion.

var isoDateFormat = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d*)?Z$/;
function parseIsoDateStrToDate(key, value){
  if (typeof value === "string" && isoDateFormat.test(value)){
    return new Date(value);
}
  return value
}
var jsonData = {date1: new Date()};
var jsonDataStr = JSON.stringify(jsonData)
var revertedJsonData = JSON.parse(jsonDataStr, parseIsoDateStrToDate);
console.log(revertedJsonData);

result: {date1: Mon Jul 01 2019 01:00:04 GMT+0800 (China Standard Time)}

Summary of JSON Date And JavaScript Date Object

  • JavaScript Date Object is Time zone and Locale Dependent
  • ISO 8601 Date Format is a general agreement for JSON Date representation
  • JavaScript do not know JSON date type

Reference

Part2: https://dev.to/imben1109/date-handling-in-angular-application-part-2-angular-http-client-and-ngx-datepicker-3fna

Discussion

pic
Editor guide