嘿,我在JavaScript中劫持了日期,强制我的客户端始终使用UTC/GMT时间,并与datetimepicker一起使用。
var daysInMonth = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
var daysInWeek = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
var daysInWeekLong = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
var months = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
var monthsShort = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
var dateReg = new RegExp("^(\\d{4})(\\d{2})(\\d{2})$");
var dateTimeReg = new RegExp("^(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{0,2})$");
var timeReg = new RegExp("^(\\d{2})(\\d{2})\\d{0,2}$");
function twoDigit(d) {
return (d < 10 ? "0" + d : "" + d);
}
Date.prototype.format = function(f) {
var day = twoDigit(this.getDate());
var dayWeek = daysInWeek[this.getDay()];
var dayWeekLong = daysInWeekLong[this.getDay()];
var month = twoDigit(this.getMonth() + 1);
var yearLong = twoDigit(this.getFullYear());
var yearShort = twoDigit(this.getFullYear().toString().substring(3,4));
var year = (f.indexOf("yyyy") > -1 ? yearLong: yearShort);
var hour24 = this.getHours();
var hour_am_pm = twoDigit((hour24 > 12 ? hour24 - 12 : hour24));
var am_pm = (hour24 >= 12 ? "PM" : "AM");
var hour24 = twoDigit(hour24);
var minute = twoDigit(this.getMinutes());
var second = twoDigit(this.getSeconds());
var monthShort = monthsShort[this.getMonth()];
var monthLong = months[this.getMonth()];
var dateString = f.replace(/month/ig, monthLong).replace(/mon/ig, monthShort).replace(/dd/ig, day).replace(/dy/ig, dayWeek).replace(/day/ig, dayWeekLong).replace(/mm/ig, month).replace(/y{2,4}/ig, year).replace(/hh24/ig, hour24).replace(/hh/ig, hour_am_pm).replace(/am_pm/ig, am_pm).replace(/mi/ig, minute).replace(/ss/ig, second);
return dateString;
}
var _f = function(item) {
Date.prototype["get" + item] = Date.prototype["getUTC" + item];
Date.prototype["set" + item] = Date.prototype["setUTC" + item];
}
var _d = ['Milliseconds', 'Seconds', 'Minutes', 'Hours', 'Date', 'Month', 'FullYear', 'Year', 'Day'];
_d.forEach(_f);
Date = class extends Date {
constructor(...options) {
if (options.length == 1 && options[0].constructor == Date) {
if (!isNaN(options[0])) {
super(options[0]);
} else {
super();
}
} else if (options.length > 0) {
if (!isNaN(options[0])) {
super(Date.UTC(...options));
} else {
super();
}
} else {
super();
}
}
};