一、时间格式转换
扩展JavaScript 的对象,添加字符串格式化函数
// 对Date的扩展,将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,
// 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子:
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.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 (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return fmt;
}
调用方法:
console.log(new Date().format("yyyy-MM-dd"));
各种时间格式如下:
yyyy:年
MM:月
dd:日
hh:1~12小时制(1-12)
HH:24小时制(0-23)
mm:分
ss:秒
S:毫秒
ps: 注意大小写
二、 时区转换
//参数i为时区值数字
function getLocalTime(i) {
//参数i为时区值数字,比如北京为东八区则输进8,西5输入-5
if (typeof i !== 'number') return;
var d = new Date();
//得到1970年一月一日到现在的秒数
var len = d.getTime();
//本地时间与GMT时间的时间偏移差
var offset = d.getTimezoneOffset() * 60000;
//得到现在的格林尼治时间=
var utcTime = len + offset;
return new Date(utcTime + 3600000 * i);
}
调用方法:
console.log("*******************东区时间************************************");
console.log("零时区-伦敦时间:" + getLocalTime(0));
console.log("东一区-柏林时间:" + getLocalTime(1));
console.log("东二区-雅典时间:" + getLocalTime(2));
console.log("东三区-莫斯科时间:" + getLocalTime(3));
console.log("东四区-时间:" + getLocalTime(4));
console.log("东五区-伊斯兰堡时间:" + getLocalTime(5));
console.log("东六区-科伦坡时间:" + getLocalTime(6));
console.log("东七区-曼谷时间:" + getLocalTime(7));
console.log("东八区-北京时间:" + getLocalTime(8));
console.log("东九区-东京时间:" + getLocalTime(9));
console.log("东十区-悉尼时间:" + getLocalTime(10));
console.log("东十二区-斐济时间:" + getLocalTime(12));
console.log("*******************西区时间************************************");
console.log("西十区-斐济时间:" + getLocalTime(-10));
console.log("西九区-阿拉斯加时间:" + getLocalTime(-9));
console.log("西八区-太平洋时间(美国和加拿大):" + getLocalTime(-8));
console.log("西七区-山地时间(美国和加拿大):" + getLocalTime(-7));
console.log("西六区-中部时间(美国和加拿大):" + getLocalTime(-6));
console.log("西五区-东部时间(美国和加拿大):" + getLocalTime(-5));
console.log("西四区-大西洋时间(加拿大):" + getLocalTime(-4));
console.log("西三区-巴西利亚时间:" + getLocalTime(-3));