JavaScript日期对象

一 : 创建日期对象
var date = new Date();  //声明构造方法,构造方法里面可以传参数,指定时间,否则就是标准时间
alert(date);    // Fri May 19 2017 19:14:37 GMT+0800 (中国标准时间)

var box = new Date('2/2/2017');
alert(box);             //Thu Feb 02 2017 00:00:00 GMT+0800
二 : 三个方法,Date.parse(),Date.UTC()和Date.now()

Date.parse()接受一个表示日期的字符串参数,然后尝试根据这个字符串返回相应的日期毫秒数

var box = Date.parse('2/2/2017');   // 一般是月/日/年
alert(box);         //返回毫秒数1485964800000

alert(Date.parse());    //没有传入日期格式参数,返回NaN

// 浏览器不同会导致很多问题
// 对于乱写的字符串返回Invalid Date(无效的日期)
var box = new Date('jwhfeuihfu');
alert(box); // Invalid Date

// 斯巴达是Invalid Date(无效的日期)
// 谷歌返回NaN
// firefox返回NaN

Date.UTC()返回表示日期的毫秒数,必须传入两个参数:年数和月份(从0开始),天数默认为1,其他参数默认为0,具体可以传入的参数有年份,月份,日期,小时,分钟,秒,毫秒。。。。

var box = Date.UTC(2017,2,3,10,58,30);
alert(box);             //1488538710000
alert(Date(box));           //Fri Feb 03 2017 10:59:39 GMT+0800(年份,基于0 的月份[0 表示1 月,1 表示2 月],月中的哪一天[1-31],小时数[0-23],分钟,秒以及毫秒)

Date.now()返回表示调用这个方法时的日期和时间的毫秒数

var start = Date.now();
doSomeThing();
function doSomeThing(){
    console.log(123);
}
var stop = Date.now();
var result = stop-start;
console.log(result);    // 4,执行这个程序用了4秒。每次执行返回的秒数不同
三 : 三个通用方法
var box = new Date(2017,2,3,11,23,45,56);
alert(box);    //Fri Mar 03 2017 11:23:45 GMT+0800
alert("toString:"+box.toString());    //Fri Mar 03 2017 11:23:45 GMT+0800
alert(""+box.toLocaleString());    //2017/3/3 上午11:23:45
alert(""+box.valueOf());      //1488511425056
四 :日期格式化的方法,因浏览器而异
var box = new Date();
alert(box); //Fri Feb 03 2017 11:50:25 GMT+0800
alert(box.toDateString());  //Fri Feb 03 2017(周几,月,日,年)
alert(box.toTimeString());  //11:50:25 GMT+0800(时,分,秒,时区)
alert(box.toLocaleDateString());    //2017/2/3
alert(box.toLocaleTimeString());    //上午11:50:25
alert(box.toUTCString());       //Fri, 03 Feb 2017 03:50:25 GMT
五 : Date()类型的方法,综合实例
var box = new Date();
alert(box.getFullYear() + '-' +(box.getMonth()+1) + '-' + box.getDate() +' ' +box.getHours() + ':' + box.getMinutes()+':'+box.getSeconds());    // 2017-5-19 19:38:33

你可能感兴趣的:(JavaScript日期对象)