js Date对象的深入理解

来源:互联网 发布:kbengine java 编辑:程序博客网 时间:2024/05/20 05:26

1.var date = new Date();
getDate() 从 Date 对象返回一个月中的某一天 (1 ~ 31)。
getDay() 从 Date 对象返回一周中的某一天 (0 ~ 6)。
getMonth() 从 Date 对象返回月份 (0 ~ 11)。
getFullYear() 从 Date 对象以四位数字返回年份。
以上四个方法是基础,分别获取日,周,月,年。
Date()没有参数,则默认为当前时间。
getHours() 返回 Date 对象的小时 (0 ~ 23)。
getMinutes() 返回 Date 对象的分钟 (0 ~ 59)。
getSeconds() 返回 Date 对象的秒数 (0 ~ 59)。

//获取当前是周几:var date = new Date();console.log(date.getDay());//6

其他用法:
toLocaleString() 根据本地时间格式,把 Date 对象转换为字符串。
toLocaleTimeString() 根据本地时间格式,把 Date 对象的时间部分转换为字符串。
toLocaleDateString() 根据本地时间格式,把 Date 对象的日期部分转换为字符串。
eg:显示当前时间:

var date = new Date();console.log(date.toLocaleString());//"2017/10/21 下午2:02:05"

2.处理任意时间:

var date = new Date("10 20 2017 14:01:20");date.getDay();//5//给Date赋初始值,即可得到某个时间下是第几周。

格式是”月 日 年 时间”,而且格式并不固定。