时间对象
使用new Date获取一个时间对象:var date = new Date()
var date=new Date();
console.log(date);
console.log(date.toUTCString());//获取格林尼治日期时间
console.log(date.toLocaleString());//获取本地日期时间
console.log(date.toLocaleDateString());//获取本地日期
console.log(date.toLocaleTimeString());//获取本地时间
时间的获取方法
- Date() 返回当日的日期和时间。
- getDate() 从 Date 对象返回一个月中的某一天 (1 ~ 31)。
- getDay() 从 Date 对象返回一周中的某一天 (0 ~ 6)。
- getMonth() 从 Date 对象返回月份 (0 ~ 11)。
- getFullYear() 从 Date 对象以四位数字返回年份。
- getYear() 请使用 getFullYear() 方法代替。
- getHours() 返回 Date 对象的小时 (0 ~ 23)。
- getMinutes() 返回 Date 对象的分钟 (0 ~ 59)。
- getSeconds() 返回 Date 对象的秒数 (0 ~ 59)。
- getMilliseconds() 返回 Date 对象的毫秒(0 ~ 999)。
- getTime() 返回 1970 年 1 月 1 日至今的毫秒数。
var date=new Date();
console.log(date.getYear());
console.log(date.getFullYear());//年
console.log(date.getMonth());//0-11月
console.log(date.getDate());//日期
console.log(date.getDay());//星期 星期日0,1-6星期一-星期六
console.log(date.getHours());//24小时制
console.log(date.getMinutes());//分钟
console.log(date.getSeconds());//秒
console.log(date.getMilliseconds());//毫秒
console.log(date.getUTCDate());//格林尼治日期
时间的设置方法
- setDate() 设置 Date 对象中月的某一天 (1 ~ 31)。
- setMonth() 设置 Date 对象中月份 (0 ~ 11)。
- setFullYear() 设置 Date 对象中的年份(四位数字)。
- setYear() 请使用 setFullYear() 方法代替。
- setHours() 设置 Date 对象中的小时 (0 ~ 23)。
- setMinutes() 设置 Date 对象中的分钟 (0 ~ 59)。
- setSeconds() 设置 Date 对象中的秒钟 (0 ~ 59)。
- setMilliseconds() 设置 Date 对象中的毫秒 (0 ~ 999)。
- setTime() 以毫秒设置 Date 对象。
设置日期时间时,如果超出范围,就会自动进位
var date=new Date();
date.setFullYear(2021);
// 设置日期时间时,如果超出范围,就会自动进位
date.setMonth(12);
console.log(date);
date.setMinutes(date.getMinutes()+5);
console.log(date);
也可以在创建date的时候,传入要设置的时间参数
参数形式有以下5种:
- new Date(“month dd,yyyy hh:mm:ss”);
- new Date(“month dd,yyyy”);
- new Date(yyyy,mth,dd,hh,mm,ss);
- new Date(yyyy,mth,dd);
- new Date(ms);
参数意义:
- month:用英文 表示月份名称,从January到December
- mth:用整数表示月份,从0(1月)到11(12月)
- dd:表示一个 月中的第几天,从1到31
- yyyy:四位数表示的年份
- hh:小时数,从0(午夜)到23(晚11点)
- mm: 分钟数,从0到59的整数
- ss:秒数,从0到59的整数
- ms:毫秒数,为大于等于0的整数
注意参数的格式,第3、4、5种一定要是整型的才可以,不能是字符串
var date=new Date("month dd,yyyy hh:mm:ss");
var date=new Date("month dd,yyyy");
var date=new new Date(yyyy,mth,dd,hh,mm,ss);
var date=new Date(yyyy,mth,dd);
var date=new Date(ms);
//下面的各种创建形式都表示2006年1月12日这一天。
new Date("January 12,2006 22:19:35");
new Date("January 12,2006");
new Date(2006,0,12,22,19,35);
new Date(2006,0,12);
new Date(1137075575000);