UNPKG

json-stringify-date

Version:

Like JSON.stringify, but preserve timezones in date objects and parse dates into Date object

59 lines 1.6 kB
import moment from 'moment'; function defaultFnCheck(key, value) { return (typeof value === 'string') && moment(value, moment.ISO_8601, true).isValid() && value.length >= 6; } let options = { utc: false, fnCheck: defaultFnCheck, fnReplacerCheck: function (key, value) { return value instanceof Date || defaultFnCheck(key, value); }, }; export function fnReviver(reviver) { return function (key, value) { if (options.fnCheck(key, value)) { value = moment(value).toDate(); } if (reviver) { value = reviver(key, value); } return value; }; } export function fnReplacer(replacer) { return function (key, value) { if (replacer) { value = replacer(key, value); } if (options.fnReplacerCheck(key, value)) { if (options.utc) { value = moment(value).utc(false).format('YYYY-MM-DDTHH:mm:ss.SSS') + "Z"; } else { value = moment(value).format('YYYY-MM-DDTHH:mm:ss.SSSZ'); } } return value; }; } export function stringify(value, replacer, space) { return JSON.stringify(value, fnReplacer(replacer), space); } export function parse(text, reviver) { return JSON.parse(text, fnReviver(reviver)); } export function getOptions() { return { ...options }; } export function setOptions(opt) { options = { ...options, ...opt }; } export default { parse, stringify, getOptions, setOptions, fnReplacer, fnReviver }; //# sourceMappingURL=index.js.map