创建
var d=new Date();
要注意的是在JavaScript中月份的值是从0到11(0表示1月)。
设置日期和时间值
设置日期和时间值有两种方法:
1、只声明距离1970年1月1日凌晨12点的毫秒数
a、直接用距离1970年1月1日凌晨12点的毫秒数
var d=new Date(0);
b、parse方法:
parse方法接受字符串为参数,把该字符串转换成日期值,返回的是毫秒数。
例如为2012年2月27日创建Date对象:
var d=new Date(Date.parse("Feb 27,2012"));
如果传给parse方法的字符串不能转换成日期,该函数返回NaN
c、UTC方法:
UTC方法也返回日期的毫秒表示,但参数为年、月、日、时、分、秒、毫秒,年、月为必选,其他为可选。
例如为2012年2月27日创建Date对象:
var d=new Date(Date.UTC(2012,1,27));
2、直接声明UTC方法接受的参数
var d=new Date(2012,1,27);
参数规则跟UTC方法相同。
Date类方法
Date类方法如下(来自:
https://m.qb5200.com/www.qb5200.com/w3school/js/jsref_obj_date.htm):
分享一个日期格式化方法 在这儿分享一个日期格式化方法,使用方法跟C#中DateTime的ToString方法类似:
Date.prototype.toString=function(format){
var time={};
time.Year=this.getFullYear();
time.TYear=(""+time.Year).substr(2);
time.Month=this.getMonth()+1;
time.TMonth=time.Month<10?"0"+time.Month:time.Month;
time.Day=this.getDate();
time.TDay=time.Day<10?"0"+time.Day:time.Day;
time.Hour=this.getHours();
time.THour=time.Hour<10?"0"+time.Hour:time.Hour;
time.hour=time.Hour<13?time.Hour:time.Hour-12;
time.Thour=time.hour<10?"0"+time.hour:time.hour;
time.Minute=this.getMinutes();
time.TMinute=time.Minute<10?"0"+time.Minute:time.Minute;
time.Second=this.getSeconds();
time.TSecond=time.Second<10?"0"+time.Second:time.Second;
time.Millisecond=this.getMilliseconds();
var oNumber=time.Millisecond/1000;
if(format!=undefined && format.replace(/\s/g,"").length>0){
format=format
.replace(/yyyy/ig,time.Year)
.replace(/yyy/ig,time.Year)
.replace(/yy/ig,time.TYear)
.replace(/y/ig,time.TYear)
.replace(/MM/g,time.TMonth)
.replace(/M/g,time.Month)
.replace(https://img.qb5200.com/download-x/dd/ig,time.TDay)
.replace(https://img.qb5200.com/download-x/d/ig,time.Day)
.replace(/HH/g,time.THour)
.replace(/H/g,time.Hour)
.replace(/hh/g,time.Thour)
.replace(/h/g,time.hour)
.replace(/mm/g,time.TMinute)
.replace(/m/g,time.Minute)
.replace(/ss/ig,time.TSecond)
.replace(/s/ig,time.Second)
.replace(/fff/ig,time.Millisecond)
.replace(/ff/ig,oNumber.toFixed(2)*100)
.replace(/f/ig,oNumber.toFixed(1)*10);
}
else{
format=time.Year+"-"+time.Month+"-"+time.Day+" "+time.Hour+":"+time.Minute+":"+time.Second;
}
return format;
}
var d=new Date();
console.log(d.toString()); //2011-12-29 11:29:43
console.log(d.toString("")); //2011-12-29 11:29:43
console.log(d.toString("yyyy-MM-dd")); //2011-12-29
console.log(d.toString("HH:mm:ss")); //11:29:43
console.log(d.toString("yyyy-MM-dd HH:mm:ss")); //2011-12-29 11:29:43
console.log(d.toString("yyyy年MM月dd日 HH:mm:ss")); //2011年12月29日 11:29:43
console.log(d.toString("yyyy-MM-dd HH:mm:ss fff")); //2011-12-29 11:29:43 862