JavaScript || Deserialize & Parse JSON Date To A Date Object & Convert Date String To Date Object Using Vanilla JavaScript
The following is a module which demonstrates how to parse a JSON date string to a date object, as well as converting a date string to a date object.
1. Convert Date String To Date Object
Using ‘Utils.parseDate‘, the example below demonstrates how to convert a date string to a date object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
// Convert string to date <script> (() => { // Convert the date strings to a date object let dates = [ '2020-01-28T00:45:08.118Z', '2020-07-29', '/Date(1238540400000)/', '/Date(1594368487704)/', '2020-11-28 03:20:35', `/Date(${Date.now()})/`, '7/14/2020 03:20:35 PM', ]; dates.forEach((dateString, index) => { // Convert the date string to a date object let date = Utils.parseDate(dateString); console.log(`\n${index + 1}. ${dateString}`); console.log('Is Date: ', date instanceof Date); console.log(date.toLocaleString()); }); })(); </script> // expected output: /* 1. 2020-01-28T00:45:08.118Z Is Date: true 1/27/2020, 4:45:08 PM 2. 2020-07-29 Is Date: true 7/28/2020, 5:00:00 PM 3. /Date(1238540400000)/ Is Date: true 3/31/2009, 4:00:00 PM 4. /Date(1594368487704)/ Is Date: true 7/10/2020, 1:08:07 AM 5. 2020-11-28 03:20:35 Is Date: true 11/28/2020, 3:20:35 AM 6. /Date(1594774590773)/ Is Date: true 7/14/2020, 5:56:30 PM 7. 7/14/2020 03:20:35 PM Is Date: true 7/14/2020, 3:20:35 PM */ |
2. Parse JSON Date String To Date Object
Using ‘Utils.parseDate‘, the example below demonstrates how to automatically parse a JSON string to a date object via a reviver function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
// Parse JSON date string to date <script> (() => { // Convert Json date in object let personJson = ` { "firstName": "Kenneth", "lastName": "P", "time": "2020-07-15T00:28:11.920Z" } `; // Deserialize json and automatically convert date string to date object let deserialized = JSON.parse(personJson, (key, value) => Utils.parseDate(value) ); console.log('Is Date: ', deserialized.time instanceof Date); console.log(deserialized.time.toLocaleString()); })(); </script> // expected output: /* Is Date: true 7/14/2020, 5:28:11 PM */ |
3. Utils.parseDate Namespace
The following is the Utils.js Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
// ============================================================================ // Author: Kenneth Perkins // Date: Jul 14, 2020 // Taken From: http://programmingnotes.org/ // File: Utils.js // Description: Javascript that handles general utility functions // ============================================================================ /** * NAMESPACE: Utils * USE: Handles general utility functions. */ var Utils = Utils || {}; (function(namespace) { 'use strict'; // -- Public data -- // Property to hold public variables and functions let exposed = namespace; /** * FUNCTION: parseDate * USE: Converts a date string to a date object. If the expression to * convert is not a valid date string, no conversion takes place and * the original value is returned. * @param value: The date value to be converted. * @return: The converted value. */ exposed.parseDate = (value) => { if (typeof value === 'string') { // Check ISO-formatted string let reISO = /^\d{4}-(0[1-9]|1[0-2])-([12]\d|0[1-9]|3[01])([T\s](([01]\d|2[0-3])\:[0-5]\d|24\:00)(\:[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3])\:?([0-5]\d)?)?)?$/; let a = reISO.exec(value); if (a) { // if so, Date() can parse it return new Date(value); } // Check Microsoft-format string let reMsAjax = /^\/Date\((d|-|.*)\)[\/|\\]$/; a = reMsAjax.exec(value); if (a) { // Parse for relevant portions let b = a[1].split(/[-+,.]/); return new Date(b[0] ? +b[0] : 0 - +b[1]); } // Check forward slash date let reDate = /\d{1,2}\/\d{1,2}\/\d{4} \d{1,2}:\d{2}|^\d{1,2}\/\d{1,2}\/\d{4}$/; a = reDate.exec(value); if (a) { // Parse for relevant portions return new Date(value); } } return value; } // -- Private data -- (function (factory) { if (typeof define === 'function' && define.amd) { define([], factory); } else if (typeof exports === 'object') { module.exports = factory(); } }(function() { return namespace; })); }(Utils)); // http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Leave a Reply