Date.prototype.setISO8601 = function (string) { var regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" + "(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?" + "(Z|(([-+])([0-9]{2})([0-9]{2})))?)?)?)?"; if (string) { var d = string.match(newRegExp(regexp)); var offset = 0; var date = newDate(d[1], 0, 1);
if (d[3]) { date.setMonth(d[3] - 1); } if (d[5]) { date.setDate(d[5]); } if (d[7]) { date.setHours(d[7]); } if (d[8]) { date.setMinutes(d[8]); } if (d[10]) { date.setSeconds(d[10]); } if (d[12]) { date.setMilliseconds(Number("0." + d[12]) * 1000); } if (d[14]) { offset = (Number(d[16]) * 60) + Number(d[17]); offset *= ((d[15] == '-') ? 1 : -1); } offset -= date.getTimezoneOffset(); time = (Number(date) + (offset * 60 * 1000)); this.setTime(Number(time)); } else { return; } }
使用
1 2
let date = newDate(); date.setISO8601('2018-07-07T22:44:14.000+0800'); // Sat Jul 07 2018 22:44:14 GMT+0800 (中国标准时间)
终于跟调试模式输出一样了
再来个日期格式化方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
//日期格式化 Date.prototype.format = function (fmt) { var o = { "M+": this.getMonth() + 1, "d+": this.getDate(), "h+": this.getHours(), "m+": this.getMinutes(), "s+": this.getSeconds(), "q+": Math.floor((this.getMonth() + 3) / 3), "S": this.getMilliseconds() }; if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); for (var k in o) if (newRegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); return fmt; }
使用
1 2 3
let date = newDate(); date.setISO8601('2018-07-07T22:44:14.000+0800'); // Sat Jul 07 2018 22:44:14 GMT+0800 (中国标准时间) let formatedDate = date.format("yyyy年MM月dd日"); // 2018年07月07日