JS时间对象操作以及时间格式化

First Post:

Last Update:

JS时间对象

取当前时间

1
var nowTime = new Date();

取年、月、日

1
2
3
nowTime.getFullYear(); // 年
nowTime.getMonth() + 1; // 月 因为 getMonth 返回的是从(0-11)的月份,故需+1
nowTime.getDate(); // 日

其他方法 get

getTime():返回从 1970 年 1 月 1 日至今的毫秒数。
getDay(): 返回当前是星期几,返回值范围 (0-6)。
getHours(): 返回时,返回值范围 (0-23)。
getMinutes():返回分,返回值范围 (0-59)。
getSeconds():返回秒,返回值范围 (0-59)。
getMilliseconds():返回毫秒,返回值范围 (0-999)。

其他方法 set

setFullYear():设置 Date 对象中的年份(四位数字)。
setMonth():设置 Date 对象中的月份,取值范围 (0 ~ 11)。
setDate():设置 Date 对象中月的某一天,取值范围 (1 ~ 31)。
setHours():设置 Date 对象中的时,取值范围 (0 ~ 23)。
setMinutes():设置 Date 对象中的分,取值范围 (0 ~ 59)。
setSeconds():设置 Date 对象中的秒,取值范围 (0 ~ 59)。
setMilliseconds():设置 Date 对象中的毫秒,取值范围 (0 ~ 999)。
setTime():以毫秒设置 Date 对象。

格式化时间格式常用方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Date.prototype.Format = function (fmt) {
// 对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
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;
}