这有点矫枉过正,但我最近特意为这样的事情制作了自己的功能
var easyDate = (function () {
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
thstndrd = ['th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th'],
toDate = function () {return new Date(Date.UTC(this.yyyy, this.MM - 1, this.dd, this.hh, this.mm, this.ss, this.ms));},
toLocaleDate = function () {return new Date(this.yyyy, this.MM - 1, this.dd, this.hh, this.mm, this.ss, this.ms);},
UTC = function UTC(d) {
return {
ms: d.getUTCMilliseconds(),
ss: d.getUTCSeconds(),
mm: d.getUTCMinutes(),
hh: d.getUTCHours(),
dd: d.getUTCDate(),
MM: d.getUTCMonth() + 1,
yyyy: d.getUTCFullYear(),
dow: d.getUTCDay(),
toDate: toDate,
toLocaleDate: toLocaleDate
}
},
easyDate = function easyDate(d) {
var o = UTC(d);
return {
dd: '' + o.dd,
th: thstndrd[o.dd % 10],
day: days[o.dow],
MM: '' + o.MM,
month: months[o.MM - 1],
year: '' + o.yyyy,
am: o.hh < 12 ? 'a.m.' : 'p.m.',
hh: o.hh < 10 ? '0' + o.hh : '' + o.hh,
h: '' + (o.hh % 12 || 12),
mm: o.mm < 10 ? '0' + o.mm : '' + o.mm,
ss: o.ss < 10 ? '0' + o.ss : '' + o.ss,
ms: ('00' + o.ms).slice(-3),
UTC: o
};
};
easyDate.UTC = UTC;
easyDate.delta = function (then, now) {
var o, p, dir = -1;
now || (now = new Date());
if (now >= then) o = UTC(now), p = UTC(then);
else o = UTC(then), p = UTC(now), now = then, dir = 1;
o.dir = dir;
o.dow = p.dow;
o.ms = o.ms - p.ms;
o.ss = o.ss - p.ss;
o.mm = o.mm - p.mm;
o.hh = o.hh - p.hh;
o.dd = o.dd - p.dd;
o.MM = o.MM - p.MM;
o.yyyy = o.yyyy - p.yyyy;
// fix negatives
if (o.ms < 0) --o.ss, o.ms = (o.ms + 1000) % 1000;
if (o.ss < 0) --o.mm, o.ss = (o.ss + 60) % 60;
if (o.mm < 0) --o.hh, o.mm = (o.mm + 60) % 60;
if (o.hh < 0) --o.dd, o.hh = (o.hh + 24) % 24;
if (o.dd < 0) { // months have different lengths
--o.MM;
now.setUTCMonth(now.getUTCMonth() + 1);
now.setUTCDate(0);
o.dd = (o.dd + now.getUTCDate()) % now.getUTCDate();
}
if (o.MM < 0) --o.yyyy, o.MM = (o.MM + 12) % 12;
return o;
};
return easyDate;
}());
并使用它
var o = easyDate(new Date());
o.month + ' ' + o.dd + o.th + ', ' + o.h + ':' + o.mm + ' ' + o.am;
// "June 18th, 7:30 p.m."
如果您注意到easyDate.delta
代码中调用的东西,是的,它也支持计算时间差异。如果您只想getUTC*
为所有事情而奔跑,那么您拥有easyDate.UTC
. :)