创建时间对象:
var objDate=new Date([arguments list]);
参数有5种形式:
1)new Date("month dd,yyyy hh:mm:ss");
2)new Date("month dd,yyyy");
3)new Date(yyyy,mth,dd,hh,mm,ss);
4)new Date(yyyy,mth,dd);
5)new Date(ms);
6)new Date()//无参数为当前系统时间
对应:
1)new Date("January 12,2006 22:19:35"); 或new Date("11 12,2006 22:19:35"); //注意字符串里的月为1-12
2) new Date("January 12,2006"); 或new Date("11 12,2006");//注意字符串里的月为1-12
3) new Date(2006,0,12,22,19,35); //数字时,这里的月为0-12
4) new Date(2006,0,12); //数字时,这里的月为0-12
5)new Date(1137075575000); //这时毫秒数,创建的时间和 GMT时间1970年1月1日之间相差的毫秒数
new Date(2020,02,0).getDate()/new Date(2020,2,0).getDate()--//返回29即返回2月的天数,第三个参数为0时,月为1-12,
经验提醒:
遇到(遇到日期的加减时候,需要用时间戳,这样可以规避跨年跨月平年润年的问题,直接24*3600*100*天数 转成日期格式即可)
javascript时间戳和日期字符串相互转换
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
// 1.获取当前时间戳(以s为单位) Date.parse(new Date());
var timestamp = Date.parse(new Date());
timestamp = timestamp / 1000;
console.log("当前时间戳为:" + timestamp)//当前时间戳为:1403149534
// 2.获取某个时间格式的时间戳 Date.parse(new Date("yyyy-MM-dd hh:mm:ss"))
var stringTime = "2014-07-10 10:21:12";
var timestamp2 = Date.parse(new Date(stringTime));
timestamp2 = timestamp2 / 1000;
//2014-07-10 10:21:12的时间戳为:1404958872
console.log(stringTime + "的时间戳为:" + timestamp2);
// 3.将当前时间换成时间格式字符串
var timestamp3 = 1403058804;//单位s
var newDate = new Date();
newDate.setTime(timestamp3 * 1000);//设置实际时间
console.log(newDate.toDateString());// "Wed Jun 18 2014" (将实际时间转为字符串)
console.log(newDate.toGMTString());// "Wed, 18 Jun 2014 02:33:24 GMT "(将实际时间转为GMT字符串)
console.log(newDate.toISOString());//"2014-06-18T02:33:24.000Z"(将实际时间转为ISO字符串)
console.log(newDate.toJSON());//"2014-06-18T02:33:24.000Z "(将实际时间转为JSON字符串)
console.log(newDate.toLocaleDateString());//"2014/6/18"(将实际时间转为LocaleDate字符串)
console.log(newDate.toLocaleString());//"2014/6/18 上午10:33:24"(将实际时间转为Locale字符串)
console.log(newDate.toLocaleTimeString());//"上午10:33:24 "
console.log(newDate.toString());//"Wed Jun 18 2014 10:33:24 GMT+0800 (中国标准时间)"
console.log(newDate.toTimeString());//"10:33:24 GMT+0800 (中国标准时间) "
console.log(newDate.toUTCString());//"Wed, 18 Jun 2014 02:33:24 GMT"
------全局格式化输出配置 年月日
Date.prototype.format = function(format) {
var date = {
"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+)/i.test(format)) {
format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
}
for (var k in date) {
if (new RegExp("(" + k + ")").test(format)) {
format = format.replace(RegExp.$1, RegExp.$1.length == 1
? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
}
}
return format;
}
console.log(newDate.format('yyyy-MM-dd h:m:s'));
</script>