parse-js
Version:
Utility library for object structure conversion.
27 lines (20 loc) • 731 B
JavaScript
;
var INVALID_DATE = 'Invalid Date';
function DateTransformer() {
var nowOnInvalid = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
if (!(this instanceof DateTransformer)) {
return this.transform(new DateTransformer(nowOnInvalid));
}
this._nowOnInvalid = nowOnInvalid;
}
DateTransformer.prototype.parse = function (value) {
var parsedDate = new Date(value);
if (parsedDate.toString() != INVALID_DATE) return parsedDate;
if (this._nowOnInvalid) return new Date();
return undefined;
};
DateTransformer.prototype.reverse = function (source) {
if (source instanceof Date && source.toJSON) return source.toJSON();
return source;
};
module.exports = DateTransformer;