javascript语法基础系列之Date用法
了解时间
格里尼治时间(GTM)
是英国郊区格林尼治天文台的时间,因为地球自转的问题,每个时区的时间是不一样的。格林尼治天文台所处的是经度为零的地方,世界上一些重大的时间都是采用的格林尼治时间。
世界标准时间(UTC)
世界标准时间(UTC)
Date
JS中的Date类型是由早期Java.util.Date类型基础之上构建的,所以保存的是距离1970年1月1日0时的毫秒数来存储时间的。
创建
1.用Date()函数创建(字符串类型)
var nowDate = Date();
得到是当前时间
是字符串类型1
2
3var nowDate = Date();
console.log(nowDate); // Tue Oct 10 2018 09:57
console.log(typeof nowDate); // string
2.使用构造函数(对象类型)
(1).不使用参数,得到当前时间
1 | var nowDate = new Date(); |
(2). 使用参数
参数是一个表示时间的字符串1
2
3
4
5
6
7
8
9
10
11
12
13
14//月、日、年、时、分、秒
// 2017-07-08 09:05:08 == 2017-07-08 9:5:8
// == 2017/7/8 9:5:8
var date = new Date('2017/7/8 09:05:08');
console.log(date); // Web Oct 11 2017 10:11:34
// 省掉 时、分、秒 默认为0(默认是标准时间)
var date = new Date('2017/10/10');
console.log(date); // Web Oct 10 2017 00:00:00
// 省掉日默认为1日
var date = new('2017/10');
console.log(date); // Web Oct 01 2017 00:00:00
// 省掉月默认为1月
var date = new Date('2017');
console.log(date); // Web Jan 01 2017 08:00:00
参数是年、月、时、分、秒、毫秒
a.年必须写的,月是从0开始,日是从1开始的
b.如果月份超过11,则年份自动增加
c.如果日超过当月应有的天数,则月份自动增加
d.时、分、秒、毫秒都是如此1
2
3// 参数是年、月、日、时、分、秒、毫秒
var date = new Date(2017,05,11,08,30,55);
console.log(date); // Sun Jun 11 2017 08:30:55
参数是一个数字
得到的是距离1970年1月1日0时参数毫秒之后的时间
注意:对应北京时间需要加8小时1
2var date = new(1508802220603);
console.log(date); // Wed Oct 11 2017 14:10:20 GWT
Date对象的方法
Get
1 | // 获取当前时间 |
Set
1 | var date = new Date(); |
转字符串
1 | // 包含年月日时分秒 |
Date 对象间的运算
两个时间对象相减,得到的时两个对象间相差的毫秒数