├── .gitattributes
├── .github
└── FUNDING.yml
├── .gitignore
├── LICENSE.md
├── bower.json
├── json.date-extensions.js
├── json.date-extensions.min.js
├── json.date-extensions.min.js.map
├── json.date-extensions.sln
├── package.json
├── readme.md
└── tests
├── JsonWithDate.txt
├── date-extensions-tests.js
├── date-tests.html
├── date-tests.js
└── json.date-extensions-tests.html
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text=auto
3 |
4 | # Custom for Visual Studio
5 | *.cs diff=csharp
6 | *.sln merge=union
7 | *.csproj merge=union
8 | *.vbproj merge=union
9 | *.fsproj merge=union
10 | *.dbproj merge=union
11 |
12 | # Standard to msysgit
13 | *.doc diff=astextplain
14 | *.DOC diff=astextplain
15 | *.docx diff=astextplain
16 | *.DOCX diff=astextplain
17 | *.dot diff=astextplain
18 | *.DOT diff=astextplain
19 | *.pdf diff=astextplain
20 | *.PDF diff=astextplain
21 | *.rtf diff=astextplain
22 | *.RTF diff=astextplain
23 |
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | github: [RickStrahl]
2 | custom: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=K677THUA2MJSE&source=url
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Build Folders (you can keep bin if you'd like, to store dlls and pdbs)
2 | [Bb]in/
3 | [Oo]bj/
4 |
5 | # mstest test results
6 | TestResults
7 |
8 | ## Ignore Visual Studio temporary files, build results, and
9 | ## files generated by popular Visual Studio add-ons.
10 |
11 | # User-specific files
12 | *.suo
13 | *.user
14 | *.sln.docstates
15 |
16 | # Build results
17 | node_modules/
18 | [Dd]ebug/
19 | [Rr]elease/
20 | x64/
21 | *_i.c
22 | *_p.c
23 | *.ilk
24 | *.meta
25 | *.mht
26 | *.obj
27 | *.pch
28 | *.pdb
29 | *.pgc
30 | *.pgd
31 | *.rsp
32 | *.sbr
33 | *.tlb
34 | *.tli
35 | *.tlh
36 | *.tmp
37 | *.log
38 | *.vspscc
39 | *.vssscc
40 | *.DotSettings
41 | .builds
42 |
43 |
44 | # Visual C++ cache files
45 | ipch/
46 | *.aps
47 | *.ncb
48 | *.opensdf
49 | *.sdf
50 |
51 | # Visual Studio profiler
52 | *.psess
53 | *.vsp
54 | *.vspx
55 |
56 | # Guidance Automation Toolkit
57 | *.gpState
58 |
59 | # ReSharper is a .NET coding add-in
60 | _ReSharper*
61 |
62 | # NCrunch
63 | *.ncrunch*
64 | .*crunch*.local.xml
65 |
66 | # Installshield output folder
67 | [Ee]xpress
68 |
69 | # DocProject is a documentation generator add-in
70 | DocProject/buildhelp/
71 | DocProject/Help/*.HxT
72 | DocProject/Help/*.HxC
73 | DocProject/Help/*.hhc
74 | DocProject/Help/*.hhk
75 | DocProject/Help/*.hhp
76 | DocProject/Help/Html2
77 | DocProject/Help/html
78 |
79 | # Click-Once directory
80 | publish
81 |
82 | # Publish Web Output
83 | *.Publish.xml
84 |
85 | # NuGet Packages Directory
86 | packages
87 |
88 | # Windows Azure Build Output
89 | csx
90 | *.build.csdef
91 |
92 | # Windows Store app package directory
93 | AppPackages/
94 |
95 | thumbs.db
96 |
97 | # Others
98 | [Bb]in
99 | [Oo]bj
100 | sql
101 | TestResults
102 | [Tt]est[Rr]esult*
103 | *.Cache
104 | ClientBin
105 | [Ss]tyle[Cc]op.*
106 | ~$*
107 | *.dbmdl
108 | Generated_Code #added for RIA/Silverlight projects
109 |
110 | #Html Help Builder
111 | HelpFile/_*.htm
112 | HelpFile/index*.*
113 | HelpFile/keywords.htm
114 | HelpFile/*.chm
115 | HelpFile/*.hh*
116 | HelpFile/*.zip
117 | HelpFile/*_recover.*
118 |
119 | # Backup & report files from converting an old project file to a newer
120 | # Visual Studio version. Backup files are not needed, because we have git ;-)
121 | _UpgradeReport_Files/
122 | Backup*/
123 | UpgradeLog*.XML
124 |
125 | OrderLineImages_Originals
126 | Temp
127 | /Libs/PullWestwindLibs.bat
128 | .idea
129 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | MIT License
2 | ===========
3 |
4 | Copyright (c) 2010-2019 West Wind Technologies
5 |
6 | Permission is hereby granted, free of charge, to any person obtaining a copy
7 | of this software and associated documentation files (the "Software"), to deal
8 | in the Software without restriction, including without limitation the rights
9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 | copies of the Software, and to permit persons to whom the Software is
11 | furnished to do so, subject to the following conditions:
12 |
13 | The above copyright notice and this permission notice shall be included in all
14 | copies or substantial portions of the Software.
15 |
16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 | SOFTWARE.
--------------------------------------------------------------------------------
/bower.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "json.date-extensions",
3 | "version": "1.2.1",
4 | "main": "json.date-extensions.js",
5 | "license": "MIT",
6 | "ignore": [
7 | "*.sln",
8 | ".*",
9 | "tests"
10 | ],
11 | "keywords": [
12 | "json",
13 | "date"
14 | ],
15 | "homepage": "https://github.com/RickStrahl/json.date-extensions"
16 | }
--------------------------------------------------------------------------------
/json.date-extensions.js:
--------------------------------------------------------------------------------
1 | /*
2 | * JSON Date Extensions - JSON date parsing extensions
3 | * Version 1.2.1
4 | * https://github.com/RickStrahl/json.date-extensions
5 | * (c) 2013-2015 Rick Strahl, West Wind Technologies
6 | *
7 | * Released under MIT License
8 | * http://en.wikipedia.org/wiki/MIT_License
9 | */
10 | (function (undefined) {
11 | "use strict";
12 |
13 | if (JSON && !JSON.dateParser) {
14 | var reISO = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.{0,1}\d*))(?:Z|(\+|-)([\d|:]*))?$/;
15 | var reMsAjax = /^\/Date\((d|-|.*)\)[\/|\\]$/;
16 |
17 | ///
18 | /// set this if you want MS Ajax Dates parsed
19 | /// before calling any of the other functions
20 | ///
21 | JSON.parseMsAjaxDate = false;
22 |
23 | JSON.useDateParser = function(reset) {
24 | ///
25 | /// Globally enables JSON date parsing for JSON.parse().
26 | /// Replaces the default JSON.parse() method and adds
27 | /// the datePaser() extension to the processing chain.
28 | ///
29 | /// when set restores the original JSON.parse() function
30 |
31 | // if any parameter is passed reset
32 | if (reset !== undefined) {
33 | if (JSON._parseSaved) {
34 | JSON.parse = JSON._parseSaved;
35 | JSON._parseSaved = null;
36 | }
37 | } else {
38 | if (!JSON._parseSaved) {
39 | JSON._parseSaved = JSON.parse;
40 | JSON.parse = JSON.parseWithDate;
41 | }
42 | }
43 | };
44 |
45 | ///
46 | /// Creates a new filter that processes dates and also delegates to a chain filter optionaly.
47 | ///
48 | /// property name that is parsed
49 | /// returns a new chainning filter for dates
50 | var createDateParser = function(chainFilter) {
51 | return function(key, value) {
52 | var parsedValue = value;
53 | if (typeof value === 'string') {
54 | var a = reISO.exec(value);
55 | if (a) {
56 | parsedValue = new Date(value);
57 | } else if (JSON.parseMsAjaxDate) {
58 | a = reMsAjax.exec(value);
59 | if (a) {
60 | var b = a[1].split(/[-+,.]/);
61 | parsedValue = new Date(b[0] ? +b[0] : 0 - +b[1]);
62 | }
63 | }
64 | }
65 | if (chainFilter !== undefined)
66 | return chainFilter(key, parsedValue);
67 | else
68 | return parsedValue;
69 | };
70 | }
71 |
72 | ///
73 | /// A filter that can be used with JSON.parse to convert dates.
74 | ///
75 | /// property name that is parsed
76 | /// property value
77 | /// returns date or the original value if not a date string
78 | JSON.dateParser = createDateParser();
79 |
80 | JSON.parseWithDate = function(json, chainFilter) {
81 | ///
82 | /// Wrapper around the JSON.parse() function that adds a date
83 | /// filtering extension. Returns all dates as real JavaScript dates.
84 | ///
85 | /// JSON to be parsed
86 | /// parsed value or object
87 | var parse = JSON._parseSaved ? JSON._parseSaved : JSON.parse;
88 | try {
89 | var res = parse(json, createDateParser(chainFilter));
90 | return res;
91 | } catch (e) {
92 | // orignal error thrown has no error message so rethrow with message
93 | throw new Error("JSON content could not be parsed");
94 | }
95 | };
96 |
97 | JSON.dateStringToDate = function(dtString, nullDateVal) {
98 | ///
99 | /// Converts a JSON ISO or MSAJAX date or real date a date value.
100 | /// Supports both JSON encoded dates or plain date formatted strings
101 | /// (without the JSON string quotes).
102 | /// If you pass a date the date is returned as is. If you pass null
103 | /// null or the nullDateVal is returned.
104 | ///
105 | /// Date String in ISO or MSAJAX format
106 | /// value to return if date can't be parsed
107 | /// date or the nullDateVal (null by default)
108 | if (!nullDateVal)
109 | nullDateVal = null;
110 |
111 | if (!dtString)
112 | return nullDateVal; // empty
113 |
114 | if (dtString.getTime)
115 | return dtString; // already a date
116 |
117 | if (dtString[0] === '"' || dtString[0] === "'")
118 | // strip off JSON quotes
119 | dtString = dtString.substr(1, dtString.length - 2);
120 |
121 | var a = reISO.exec(dtString);
122 | if (a)
123 | return new Date(dtString);
124 |
125 | if (!JSON.parseMsAjaxDate)
126 | return nullDateVal;
127 |
128 | a = reMsAjax.exec(dtString);
129 | if (a) {
130 | var b = a[1].split(/[-,.]/);
131 | return new Date(+b[0]);
132 | }
133 | return nullDateVal;
134 | };
135 | }
136 | })();
137 |
--------------------------------------------------------------------------------
/json.date-extensions.min.js:
--------------------------------------------------------------------------------
1 | /* JSON Date Extensions, Version 1.2.1 */
2 | (function(n){"use strict";var t,i,r;JSON&&!JSON.dateParser&&(t=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.{0,1}\d*))(?:Z|(\+|-)([\d|:]*))?$/,i=/^\/Date\((d|-|.*)\)[\/|\\]$/,JSON.parseMsAjaxDate=!1,JSON.useDateParser=function(t){t!==n?JSON._parseSaved&&(JSON.parse=JSON._parseSaved,JSON._parseSaved=null):JSON._parseSaved||(JSON._parseSaved=JSON.parse,JSON.parse=JSON.parseWithDate)},r=function(r){return function(u,f){var o=f,e,s;return typeof f=="string"&&(e=t.exec(f),e?o=new Date(f):JSON.parseMsAjaxDate&&(e=i.exec(f),e&&(s=e[1].split(/[-+,.]/),o=new Date(s[0]?+s[0]:0-+s[1])))),r!==n?r(u,o):o}},JSON.dateParser=r(),JSON.parseWithDate=function(n,t){var i=JSON._parseSaved?JSON._parseSaved:JSON.parse;try{return i(n,r(t))}catch(u){throw new Error("JSON content could not be parsed");}},JSON.dateStringToDate=function(n,r){var u,f;return(r||(r=null),!n)?r:n.getTime?n:((n[0]==='"'||n[0]==="'")&&(n=n.substr(1,n.length-2)),u=t.exec(n),u)?new Date(n):JSON.parseMsAjaxDate?(u=i.exec(n),u)?(f=u[1].split(/[-,.]/),new Date(+f[0])):r:r})})();
3 | //# sourceMappingURL=json.date-extensions.min.js.map
4 |
--------------------------------------------------------------------------------
/json.date-extensions.min.js.map:
--------------------------------------------------------------------------------
1 | {
2 | "version":3,
3 | "file":"json.date-extensions.min.js",
4 | "lineCount":1,
5 | "mappings":"CASC,QAAS,CAACA,CAAD,CAAY,CAClB,Y,CAGI,IAAIC,EACAC,EAmCAC,CApC+F,CADnGC,IAAK,EAAG,CAACA,IAAIC,W,GACTJ,CAAM,CAAyF,uF,CAC/FC,CAAS,CAA+B,6B,CAM5CE,IAAIE,gBAAiB,CAAE,CAAA,CAAK,CAE5BF,IAAIG,cAAe,CAAEC,QAAQ,CAACC,CAAD,CAAQ,CAS7BA,CAAM,GAAIT,CAAd,CACQI,IAAIM,Y,GACJN,IAAIO,MAAO,CAAEP,IAAIM,YAAY,CAC7BN,IAAIM,YAAa,CAAE,KAH3B,CAMSN,IAAIM,Y,GACLN,IAAIM,YAAa,CAAEN,IAAIO,MAAM,CAC7BP,IAAIO,MAAO,CAAEP,IAAIQ,eAjBQ,CAoBpC,CAOGT,CAAiB,CAAEA,QAAQ,CAACU,CAAD,CAAc,CACzC,OAAO,QAAQ,CAACC,CAAG,CAAEC,CAAN,CAAa,CACxB,IAAIC,EAAcD,EAEVE,EAMQC,CARO,CAavB,OAZI,OAAOH,CAAM,EAAI,Q,GACbE,CAAE,CAAEhB,CAAKkB,KAAK,CAACJ,CAAD,C,CACdE,CAAJ,CACID,CAAY,CAAE,IAAII,IAAI,CAACL,CAAD,CAD1B,CAEWX,IAAIE,gB,GACXW,CAAE,CAAEf,CAAQiB,KAAK,CAACJ,CAAD,CAAO,CACpBE,C,GACIC,CAAE,CAAED,CAAE,CAAA,CAAA,CAAEI,MAAM,CAAS,QAAT,C,CAClBL,CAAY,CAAE,IAAII,IAAI,CAACF,CAAE,CAAA,CAAA,CAAG,CAAE,CAACA,CAAE,CAAA,CAAA,CAAG,CAAE,CAAE,CAAE,CAACA,CAAE,CAAA,CAAA,CAAvB,I,CAI9BL,CAAY,GAAIb,CAAhB,CACOa,CAAW,CAACC,CAAG,CAAEE,CAAN,CADlB,CAGOA,CAjBa,CADa,C,CA4B7CZ,IAAIC,WAAY,CAAEF,CAAgB,CAAA,CAAE,CAEpCC,IAAIQ,cAAe,CAAEU,QAAQ,CAACC,CAAI,CAAEV,CAAP,CAAoB,CAO7C,IAAIF,EAAQP,IAAIM,YAAa,CAAEN,IAAIM,YAAa,CAAEN,IAAIO,MAAM,CAC5D,GAAI,CAEA,OADUA,CAAK,CAACY,CAAI,CAAEpB,CAAgB,CAACU,CAAD,CAAvB,CADf,OAGKW,EAAG,CAER,MAAM,IAAIC,KAAK,CAAC,kCAAD,CAAoC,CAF3C,CAXiC,CAehD,CAEDrB,IAAIsB,iBAAkB,CAAEC,QAAQ,CAACC,CAAQ,CAAEC,CAAX,CAAwB,CAwBpD,IAAIZ,EASIC,CAToB,CAY5B,OAzBKW,C,GACDA,CAAY,CAAE,KAAI,CAElB,CAACD,EAHL,CAIWC,CAJX,CAMID,CAAQE,QAAR,CACOF,CADP,GAGAA,CAAS,CAAA,CAAA,CAAG,GAAI,GAAI,EAAGA,CAAS,CAAA,CAAA,CAAG,GAAI,I,GAEvCA,CAAS,CAAEA,CAAQG,OAAO,CAAC,CAAC,CAAEH,CAAQI,OAAQ,CAAE,CAAtB,EAAwB,CAElDf,CAAE,CAAEhB,CAAKkB,KAAK,CAACS,CAAD,C,CACdX,EALJ,CAMW,IAAIG,IAAI,CAACQ,CAAD,CANnB,CAQKxB,IAAIE,gBAAL,EAGJW,CAAE,CAAEf,CAAQiB,KAAK,CAACS,CAAD,CAAU,CACvBX,EADJ,EAEQC,CAAE,CAAED,CAAE,CAAA,CAAA,CAAEI,MAAM,CAAQ,OAAR,C,CACX,IAAID,IAAI,CAAC,CAACF,CAAE,CAAA,CAAA,CAAJ,EAHnB,CAKOW,CARH,CACOA,CA7ByC,EAvF1C,EA8HpB,CAAA,CAAE",
6 | "sources":["json.date-extensions.js"],
7 | "names":["undefined","reISO","reMsAjax","createDateParser","JSON","dateParser","parseMsAjaxDate","useDateParser","JSON.useDateParser","reset","_parseSaved","parse","parseWithDate","chainFilter","key","value","parsedValue","a","b","exec","Date","split","JSON.parseWithDate","json","e","Error","dateStringToDate","JSON.dateStringToDate","dtString","nullDateVal","getTime","substr","length"]
8 | }
9 |
--------------------------------------------------------------------------------
/json.date-extensions.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 2013
4 | VisualStudioVersion = 12.0.21005.1
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{E24C65DC-7377-472B-9ABA-BC803B73C61A}") = "json.date-extensions", "http://localhost:56663", "{62095A1B-0EF7-44B9-8AF6-5210F7F560DB}"
7 | ProjectSection(WebsiteProperties) = preProject
8 | UseIISExpress = "true"
9 | TargetFrameworkMoniker = ".NETFramework,Version%3Dv4.0"
10 | Debug.AspNetCompiler.VirtualPath = "/localhost_56663"
11 | Debug.AspNetCompiler.PhysicalPath = "..\json.date-extensions\"
12 | Debug.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_56663\"
13 | Debug.AspNetCompiler.Updateable = "true"
14 | Debug.AspNetCompiler.ForceOverwrite = "true"
15 | Debug.AspNetCompiler.FixedNames = "false"
16 | Debug.AspNetCompiler.Debug = "True"
17 | Release.AspNetCompiler.VirtualPath = "/localhost_56663"
18 | Release.AspNetCompiler.PhysicalPath = "..\json.date-extensions\"
19 | Release.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_56663\"
20 | Release.AspNetCompiler.Updateable = "true"
21 | Release.AspNetCompiler.ForceOverwrite = "true"
22 | Release.AspNetCompiler.FixedNames = "false"
23 | Release.AspNetCompiler.Debug = "False"
24 | SlnRelativePath = "..\json.date-extensions\"
25 | EndProjectSection
26 | EndProject
27 | Global
28 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
29 | Debug|Any CPU = Debug|Any CPU
30 | EndGlobalSection
31 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
32 | {62095A1B-0EF7-44B9-8AF6-5210F7F560DB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
33 | {62095A1B-0EF7-44B9-8AF6-5210F7F560DB}.Debug|Any CPU.Build.0 = Debug|Any CPU
34 | EndGlobalSection
35 | GlobalSection(SolutionProperties) = preSolution
36 | HideSolutionNode = FALSE
37 | EndGlobalSection
38 | EndGlobal
39 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "json.date-extensions",
3 | "version": "1.2.2",
4 | "description": "JSON date parsing extensions by extending JSON object.",
5 | "main": "json.date-extensions.js",
6 | "directories": {
7 | "test": "tests"
8 | },
9 |
10 | "scripts": {
11 | "test": "echo \"Error: no tests specified\" && exit 1"
12 | },
13 | "repository": {
14 | "type": "git",
15 | "url": "https://github.com/RickStrahl/json.date-extensions.git"
16 | },
17 | "keywords": [
18 | "JSON",
19 | "Date"
20 | ],
21 | "author": "Rick Strahl (http://weblog.west-wind.com)",
22 | "license": "MIT",
23 | "bugs": {
24 | "url": "https://github.com/RickStrahl/json.date-extensions/issues"
25 | },
26 | "homepage": "https://github.com/RickStrahl/json.date-extensions"
27 | }
28 |
--------------------------------------------------------------------------------
/readme.md:
--------------------------------------------------------------------------------
1 |
2 | # JSON Parser Date Extensions
3 | #### Date parsing extensions for the JavaScript JSON parser to provide real JavaScript dates from JSON.parse()
4 |
5 | This small JavaScript library provides for automatically parsing JSON date strings
6 | to real JavaScript dates as part of regular JSON parsing.
7 | You can parse either individual date values or complex objects containing dates
8 | and have them automatically turned into dates, unlike the default JSON parser
9 | behavior of parsing to ISO 8601 date strings.
10 |
11 | You can either manually run the date parsing or replace the JSON parser
12 | for the global scope to force *all* JSON operations to parse dates
13 | automatically, including those by other frameworks such as jQuery, angularJS etc.
14 |
15 | This library came about as part of the following blog post:
16 | * **[JavaScript JSON Date Parsing and real Dates](http://weblog.west-wind.com/posts/2014/Jan/06/JavaScript-JSON-Date-Parsing-and-real-Dates)**
17 |
18 | This library provides:
19 |
20 | * **JSON.dateParser**
21 | JSON parser extension that can be used with JSON.parse()
22 | to parse dates with explicit calls to JSON.parse().
23 |
24 | * **JSON.parseWithDate()**
25 | Function to provide a wrapper function
26 | that behaves like JSON.parse() but parses dates.
27 |
28 | * **JSON.useDateParser()**
29 | Globally replace JSON.parse() with
30 | JSON.parseWithDates to affect all JSON.parse() operations within
31 | the current page/scope. Affects all JSON operations including
32 | framework JSON parsing such as jQuery.getJSON(),
33 | Angular $http functions etc.
34 |
35 | * **JSON.dateStringToDate()**
36 | Safely converts JSON ISO and MSAJAX
37 | dates, raw ISO and MSAJAX string values and dates to JavaScript
38 | dates. This function is a simple helper to guarantee you get a
39 | date value regardless of which format the date is in with an optional
40 | override to return a known value if the date can't be resolved.
41 |
42 | ## Installation
43 | You can either use the files out of the root folder directly or you
44 | can install from one of the package repositories:
45 |
46 | ##### Bower
47 | bower install json.date-extensions
48 |
49 | ##### NPM
50 | npm install json.date-extensions
51 |
52 | ##### JSPM
53 | jspm install json.date-extensions
54 |
55 | Note this library has no exports - it only extends the JSON object with additional members you can call. You can `require` without capturing the return value.
56 |
57 | ```javascript
58 | require('json.date-extensions');
59 | JSON.useDateParser();
60 | ```
61 |
62 | or use simple script references in your HTML document:
63 |
64 | ```html
65 |
66 |
69 | ```
70 |
71 | ## Usage
72 | This library provides a simple API for changing the behavior of the JSON parser. You can either explicitly parse JSON data using provided functions or change the behavior of the parser globally.
73 |
74 | ### JSON.parseWithDate ###
75 | Manual JSON parsing with automatic date conversion:
76 |
77 | ```javascript
78 | var date = new Date();
79 | var json = JSON.stringify(date);
80 |
81 | var date2 = JSON.parseWithDate(json);
82 | console.log(date2); // date: Wed Jan 01 2014 13:28:56 GMT-1000 (Hawaiian Standard Time)
83 | ```
84 |
85 | Likewise you can apply that to complex objects that contain dates:
86 |
87 | ```javascript
88 | var obj = {
89 | id: "141923asd1",
90 | name: "rick",
91 | entered: new Date(),
92 | updated: new Date()
93 | };
94 | var json = JSON.stringify(obj);
95 |
96 | var obj2 = JSON.parseWithDate(json);
97 |
98 | equal(!obj2.entered.getTime, false, "Date should be a date object");
99 | equal(obj2.entered.toString(), obj.entered.toString(), "Dates should be equal");
100 | ```
101 |
102 |
103 | ### JSON.useDateParser ###
104 | useDateParser() can globally replace the JSON.parse() function with the
105 | JSON.parseWithDate() function, which results in automatically converting dates
106 | for all JSON operations on the global scope. This allows automatic conversions
107 | for all subsequent JSON.parse() calls including those inside of frameworks.
108 |
109 | ```javascript
110 | // enable global JSON date parsing
111 | JSON.useDateParser();
112 |
113 | var date = new Date();
114 | var json = JSON.stringify(date);
115 |
116 | // using just plain JSON.parse() should decode dates
117 | var date2 = JSON.parse(json);
118 | console.log(date2);
119 |
120 | equal(!date2.getTime, false, "Date should be a date object");
121 | equal(date2.toString(), date.toString(), "Dates should be equal");
122 |
123 | // optionally replace original parser
124 | JSON.useDateParser(false);
125 | ```
126 |
127 | The following example demonstrates using $.getJSON() with automatic
128 | date conversion:
129 |
130 | ```javascript
131 | // enable global JSON date parsing
132 | JSON.useDateParser();
133 |
134 | $.getJSON("JsonWithDate.txt")
135 | .done(function(data) {
136 | console.log("jquery result.entered: " + data.entered +
137 | " result.updated: " + data.updated);
138 |
139 | equal(!data.entered.getTime, false, "Entered should be a date");
140 | })
141 | .success(function () {
142 | // Optionally replace original parser
143 | JSON.useDateParser(false);
144 | });
145 | ```
146 |
147 | ### JSON.dateParser ###
148 | dateParser is the JSON parse extension that is used to filter dates from
149 | date strings. You can use this filter directly with JSON.parse() although
150 | I'd recommend you use JSON.parseWithDate() instead.
151 |
152 | ```javascript
153 | var obj = {
154 | id: "141923asd1",
155 | name: "rick",
156 | entered: new Date(),
157 | updated: new Date()
158 | };
159 | var json = JSON.stringify(obj);
160 |
161 | var obj2 = JSON.parse(json, JSON.dateParser);
162 |
163 | console.log(obj2.entered,obj2.updated);
164 | ```
165 |
166 | ### JSON.dateStringToDate ###
167 | dateStringToDate reliably provides JavaScript dates from JSON dates strings,
168 | plain strings in ISO or MS AJAX formats or dates. Useful when you are not
169 | converting JSON dates automatically and you need to be sure you always get
170 | consistent date values in code.
171 |
172 | All of the following should produce a date:
173 |
174 | ```javascript
175 | var date = new Date();
176 | var json = JSON.stringify(date);
177 |
178 | // JSON date
179 | var date2 = JSON.dateStringToDate(json);
180 | console.log(date2);
181 |
182 | // string ISO date
183 | date2 = JSON.dateStringToDate("2014-01-01T13:13:34.441Z");
184 | console.log(date2);
185 |
186 | date2 = JSON.dateStringToDate("2014-01-01T13:13:34.441Z");
187 | console.log(date2);
188 |
189 | // real date - just echoed back
190 | date2 = JSON.dateStringToDate(new Date());
191 | console.log(date2);
192 | ```
--------------------------------------------------------------------------------
/tests/JsonWithDate.txt:
--------------------------------------------------------------------------------
1 | {
2 | "id": "312saAs1",
3 | "name": "Jimmy Roe",
4 | "entered": "2014-01-01T23:28:56.782Z",
5 | "updated": "2014-01-01T23:28:56.782Z"
6 | }
--------------------------------------------------------------------------------
/tests/date-extensions-tests.js:
--------------------------------------------------------------------------------
1 | ///
2 | ///
3 |
4 | // Date Parser Extension
5 | test("dateParserExtension", function () {
6 | var date = new Date();
7 | var json = JSON.stringify(date);
8 |
9 | var date2 = JSON.parse(json, JSON.dateParser);
10 | console.log(date2);
11 |
12 | equal(!date2.getTime, false, "Date should be a date object");
13 | equal(date2.toString(), date.toString(), "Dates should be equal");
14 | });
15 |
16 |
17 | // Date Parser Extension with object dates
18 | test("dateParserExtensionObject", function () {
19 | var obj = {
20 | id: "141923asd1",
21 | name: "rick",
22 | entered: new Date(),
23 | updated: new Date()
24 | };
25 | var json = JSON.stringify(obj);
26 |
27 | var obj2 = JSON.parse(json, JSON.dateParser);
28 |
29 | equal(!obj2.entered.getTime, false, "Date should be a date object");
30 | equal(obj2.entered.toString(), obj.entered.toString(), "Dates should be equal");
31 | });
32 |
33 | test("parseWithDate", function () {
34 | var date = new Date();
35 | var json = JSON.stringify(date);
36 |
37 | var date2 = JSON.parseWithDate(json);
38 | console.log(date2);
39 |
40 | equal(!date2.getTime, false, "Date should be a date object");
41 | equal(date2.toString(), date.toString(), "Dates should be equal");
42 | });
43 |
44 |
45 | test("parseWithDateObject", function () {
46 | var obj = {
47 | id: "141923asd1",
48 | name: "rick",
49 | entered: new Date(),
50 | updated: new Date()
51 | };
52 | var json = JSON.stringify(obj);
53 |
54 | var obj2 = JSON.parseWithDate(json);
55 |
56 | equal(!obj2.entered.getTime, false, "Date should be a date object");
57 | equal(obj2.entered.toString(), obj.entered.toString(), "Dates should be equal");
58 | });
59 |
60 |
61 | // useDateParser global replace operation
62 | test("useDateParser", function () {
63 | // enable global JSON parsing
64 | JSON.useDateParser();
65 |
66 | var date = new Date();
67 | var json = JSON.stringify(date);
68 |
69 | // using just plain JSON.parse() should decode dates
70 | var date2 = JSON.parse(json);
71 | console.log(date2);
72 |
73 | equal(!date2.getTime, false, "Date should be a date object");
74 | equal(date2.toString(), date.toString(), "Dates should be equal");
75 |
76 | // replace original parser
77 | JSON.useDateParser();
78 | });
79 |
80 |
81 | test("dateStringToDateJson", function () {
82 | var date = new Date();
83 | var json = JSON.stringify(date);
84 |
85 | var date2 = JSON.dateStringToDate(json);
86 | equal(date2.toString(), date.toString(), "Deserialized date should match original date");
87 | });
88 |
89 | test("ISODateFormatsDateStringToDate", function () {
90 |
91 | var date = JSON.dateStringToDate("2014-01-01T13:13:34.441Z");
92 | equal(date !== null, true, "Deserialized date string should be a date");
93 |
94 | date = JSON.dateStringToDate("2014-01-01T13:13:34.41Z");
95 | equal(date !== null, true, "Deserialized date string should be a date");
96 |
97 | date = JSON.dateStringToDate("2014-01-01T13:13:34.01Z");
98 | equal(date !== null, true, "Deserialized date string should be a date");
99 |
100 | date = JSON.dateStringToDate("2014-01-01T13:13:34.11Z");
101 | equal(date !== null, true, "Deserialized date string should be a date");
102 |
103 | date = JSON.dateStringToDate("2014-01-01T13:13:34Z"); // no decimals
104 | equal(date !== null, true, "Deserialized date string should be a date");
105 |
106 | date = JSON.dateStringToDate("2014-01-01T04:13:00+00:00");
107 | equal(date !== null, true, "Deserialized date string should be a date ");
108 |
109 | });
110 |
111 | test("dateStringToDateMsAjaxString", function () {
112 | JSON.parseMsAjaxDate = true; // default is off
113 | var date2 = JSON.dateStringToDate("\/Date(1388804145879)\/");
114 | JSON.parseWithDate = false; // turn off for subsequent tests
115 |
116 | console.log(date2); // should be a date (or null on failure)
117 | equal(date2 !== null, true, "Deserialized date string should be a date");
118 | });
119 |
120 | test("dateStringToDateDate", function () {
121 |
122 | var date2 = JSON.dateStringToDate(new Date());
123 |
124 | equal(!date2.getTime, false, "Deserialized date string should be a date");
125 | });
126 |
127 | test("dateStringToDateNull", function () {
128 |
129 | var date2 = JSON.dateStringToDate(null);
130 | equal(!date2, true, "Date should be null");
131 | });
132 |
133 |
134 | // jQuery JSON from AJAX
135 | test("useDateParserAjax", function () {
136 | JSON.useDateParser();
137 | stop();
138 |
139 | $.getJSON("JsonWithDate.txt")
140 | .done(function(data) {
141 | start();
142 | console.log("jquery result.entered: " + data.entered +
143 | " result.updated: " + data.updated);
144 |
145 | equal(data.entered != null && data.entered.getTime != null, true,
146 | "data.entered should be a Date. Value: " + data.entered + " Note this error may fail randomly due to async setting for useDateParser(). To see this test work properly consistently run individually.");
147 |
148 | // replace original parser
149 | JSON.useDateParser(false);
150 | })
151 | .error(function () {
152 | start();
153 | console.log("error");
154 | equal(false, true, "Callback failed - no date was converted.");
155 | // replace original parser
156 | JSON.useDateParser(false);
157 | });
158 |
159 | });
--------------------------------------------------------------------------------
/tests/date-tests.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | QUnit Example
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/tests/date-tests.js:
--------------------------------------------------------------------------------
1 | // default json behavior test - date as string
2 | test("defaultJson", function () {
3 | var date = new Date();
4 | var json = JSON.stringify(date);
5 | console.log("JSON: " + json);
6 |
7 | var date2 = JSON.parse(json);
8 | console.log("Result (string): " + date2);
9 |
10 | equal(typeof (date2) === "string", true, "Date should result in a string");
11 | });
12 |
13 | // using date constructor to convert JSON parsed date
14 | test("decodeJsonDate", function () {
15 | var date = new Date();
16 | var json = JSON.stringify(date);
17 | var dateStr = JSON.parse(json);
18 |
19 | console.log(dateStr); // 2014-01-01T23:28:56.782Z
20 |
21 | var date2 = new Date(dateStr);
22 | console.log(date2); // Wed Jan 01 2014 13:28:56 GMT-1000 (Hawaiian Standard Time)
23 |
24 | equal(!date2.getTime, false, "Date should be a date object");
25 | equal(date2.toString(), date.toString(), "Dates should be equal");
26 | });
27 |
--------------------------------------------------------------------------------
/tests/json.date-extensions-tests.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | QUnit Example
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------