JavaScript中日期函数的相关操作知识
时间对象是一个我们经常要用到的对象,无论是做时间输出、时间判断等操作时都与这个对象离不开。除开JavaScript中的时间对象外,在VbScript中也有许多的时间对象,而且非常好用。下面还是按照我们的流程来进行讲解JavaScript中日期函数。
newDate()
newDate(milliseconds)
newDate(datestring)
newDate(year,month)
newDate(year,month,day)
newDate(year,month,day,hours)
newDate(year,month,day,hours,minutes)
newDate(year,month,day,hours,minutes,seconds)
newDate(year,month,day,hours,minutes,seconds,microseconds)
下面对
1.newDate(),没有参数的时候,创建的是当前时间日期对象。
2.newDate(milliseconds),当参数为数字的时候,那么这个参数就是时间戳,被视为毫秒,创建一个距离1970年1月一日指定毫秒的时间日期对象。
3.newDate(datestring),此参数是一个字符串,并且此字符串一定能够使用Date.parse()转换。
4.以下六个构造函数是精确定义:
1).year,是一个整数,如果是0-99,那么在此基础上加1900,其他的都原样返回。
2).month,是一个整数,范围是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>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/>
</head>
<body>
</body>
</html>
<script>
window.onload=function(){
varnow=newDate();//当前系统时间
varshijianchuo=now.getTime();//获取当前时间戳
alert("时间戳:"+shijianchuo);
varnowdate=newDate(shijianchuo);//将时间戳转化为日期对象
varnowtime=nowdate.Format("yyyy-MM-ddhh:mm:ss");//格式化当前系统时间,相当于将时间戳转化为年月日时分秒了
alert("当前时间:"+nowtime);
}
/*
日期格式化:
对Date的扩展,将Date转化为指定格式的String
年(y)可以用1-4个占位符,季度(q)可以用1-2个占位符.
月(M)、日(d)、小时(h)、分(m)、秒(s)可以用1-2个占位符.
毫秒(S)只能用1个占位符(是1-3位的数字)
例子:
(newDate()).Format("yyyy-MM-ddhh:mm:ss.S")
(newDate()).Format("yyyy-MM-ddhh:mm:ss.S毫秒第qq季度")
*/
Date.prototype.Format=function(fmt){
varo={
"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(varkino)
if(newRegExp("("+k+")").test(fmt))fmt=fmt.replace(RegExp.$1,(RegExp.$1.length==1)?
(o[k]):(("00"+o[k]).substr((""+o[k]).length)));
returnfmt;
}
</script>