js时间上的操作

3,412 阅读1分钟
1.首先了解一下javascript Date对象的一些基本方法:

可以打印一下Date对象

console.dir(Date)

可以看一下它的原型 prototype,里面是Date对象的function

下面就简单介绍几种常用的方法:(详细请看www.w3school.com.cn/jsref/jsref…)

var myDate = new Date();
myDate.getDate();   //返回日期
myDate.getDay();    //返回周几(0~6,0为周日)
myDate.getMouth();    //返回月份
mydate.getFullYear();    //返回年份
myDate.getHours();    //返回小时(0~23)
myDate.getMinutes();    //返回分钟(0~59)
myDate.getSeconds();     //返回秒数(0~59)

注:get如果在没有设置时间的情况下,获取的时间日期为当天的;

所以对应上面的,还有set的函数:

//假设今天为2014-12-14
var myDate = new Date();
myDate.getDate();  //14
myDate.setDate(13);  //设置日期为13号
myDate.getDate();  //13

#####2.时间的比较
var time1 = new Date();
console.log(time1);  //Sun Dec 14 2014 11:12:15 GMT+0800 (CST)
console.log(typeof time1);  //object
var time2 = new Date();
console.log(time2);  //Sun Dec 14 2014 11:15:11 GMT+0800 (CST)
console.log(time2 > time1);  //true
//时间的差
time2 - time1  //176288

时间的差为毫秒数,两者的时间差为将近176秒,差为176288毫秒。

#####注:关于时间方面的操作可以借助第三方的库(Moment.js