本文详细解析JavaScript中Date对象的多种构造函数用法。涵盖无参创建当前时间、基于毫秒数转换、字符串解析以及精确的年、月、日、时、分、秒甚至微秒参数组合。重点说明年份0-99的特殊处理规则及月份0-11的索引范围,帮助开发者准确创建指定时间对象。
JavaScript Date对象概述
在Web开发中,处理时间数据是常见需求,无论是进行时间展示、逻辑判断还是排序,都离不开对时间对象的操作。虽然VbScript等语言也提供了丰富的时间处理功能,但本文主要聚焦于JavaScript中日期函数的具体使用方法,按照标准流程进行详细讲解。
Date构造函数参数详解
new Date()
new Date(milliseconds)
new Date(datestring)
new Date(year, month)
new Date(year, month, day)
new Date(year, month, day, hours)
new Date(year, month, day, hours, minutes)
new Date(year, month, day, hours, minutes, seconds)
new Date(year, month, day, hours, minutes, seconds, microseconds)
接下来,我们将对上述几种构造函数进行逐一解析。
1. 当调用new Date()且不带任何参数时,系统会返回当前时刻的时间日期对象。
2. 当参数为数字类型时,即new Date(milliseconds),该数字被视为时间戳(毫秒数)。系统会创建一个距离1970年1月1日指定毫秒数的时间日期对象。
3. 当参数为字符串类型时,即new Date(datestring),该字符串必须能够被Date.parse()方法成功解析,否则可能返回Invalid Date。
4. 以下六种构造函数用于精确定义时间,各参数含义如下:
1). year:代表年份,必须为整数。若传入的值为0到99之间,系统会自动加上1900(例如传入50代表1950年);其他数值则原样使用。
2). month:代表月份,必须为整数,取值范围是0到11,其中0代表一月,11代表十二月。
3). day:代表日期,必须为整数,取值范围是1到31。
4). hours:代表小时,必须为整数,取值范围是0到23。
5). minutes:代表分钟,必须为整数,取值范围是0到59。
6). seconds:代表秒数,必须为整数,取值范围是0到59。
7). microseconds:代表微秒,必须为整数,取值范围是0到9999。
时间戳转换与格式化示例
<html>
<head>
<title>时间戳转化为年月日时分秒</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
</body>
</html>
<script>
window.onload=function(){
var now=new Date();//当前系统时间
var shijianchuo = now.getTime();//获取当前时间戳
alert("时间戳:"+shijianchuo);
var nowdate = new Date(shijianchuo);//将时间戳转化为日期对象
var nowtime=nowdate.Format("yyyy-MM-dd hh:mm:ss");//格式化当前系统时间,相当于将时间戳转化为年月日时分秒了
alert("当前时间:"+nowtime);
}
/*
日期格式化:
对Date的扩展,将 Date 转化为指定格式的String
年(y)可以用1-4个占位符,季度(q)可以用1-2个占位符.
月(M)、日(d)、小时(h)、分(m)、秒(s)可以用1-2个占位符.
毫秒(S)只能用1个占位符(是1-3位的数字)
例子:
(new Date()).Format("yyyy-MM-dd hh:mm:ss.S")
(new Date()).Format("yyyy-MM-dd hh:mm:ss.S毫秒 第qq季度")
*/
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;
}
</script>