javascript语法基础系列之Date用法


javascript语法基础系列之Date用法

了解时间

格里尼治时间(GTM)

是英国郊区格林尼治天文台的时间,因为地球自转的问题,每个时区的时间是不一样的。格林尼治天文台所处的是经度为零的地方,世界上一些重大的时间都是采用的格林尼治时间。

世界标准时间(UTC)

世界标准时间(UTC)

Date

JS中的Date类型是由早期Java.util.Date类型基础之上构建的,所以保存的是距离1970年1月1日0时的毫秒数来存储时间的。

创建

1.用Date()函数创建(字符串类型)

var nowDate = Date();
得到是当前时间
是字符串类型

1
2
3
var nowDate = Date();
console.log(nowDate); // Tue Oct 10 2018 09:57
console.log(typeof nowDate); // string

2.使用构造函数(对象类型)

(1).不使用参数,得到当前时间

1
2
var nowDate = new Date();
console.log(typeof nowDate) // object

(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
2
var date = new(1508802220603);
console.log(date); // Wed Oct 11 2017 14:10:20 GWT

Date对象的方法

Get

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 获取当前时间
var date = new Date();
// 获取年
var year = date.getFullYear();
// 获取月
var month = date.getMonth();
// 获取日
var Date = date.getDate();
// 获取星期
var day = date.getDay();
// 获取时
var hour = date.getHours();
// 获取分
var minute = date.getMinutes();
// 获取秒
var seconds = date.getSeconds();
// 获取毫秒
var millSecond = date.getMillSeconds();
// 获取当前时间距离 1970年1月1日0时的毫秒数
var dutation = date.getTime();

Set

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var date = new Date();
// 设置年
var Year = date.setFullYear(2017);
// 设置月 月是从0开始 如果大于等于12,年份增加
var Month = date.setMonth(10);
// 设置日 如果日大于当月应有的天数,月增加
var Date = date.setDate();
// 设置星期 注意星期一般不设置
// 设置时 如果时大于23 日增加
var Hour = date.setHours(08);
// 设置分钟 如果分钟大于59 时增加
var Minute = date.setMinutes(54);
// 设置秒 如果秒大于 59 分增加
var Second = date.setSeconds(55);
// 设置毫秒 如果毫秒大于999 秒增加
var MillSecond = date.setMillseconds(666);
// 设置距离1970年1月1日0时毫秒数
var duration = date.setTime(1507703240504);

转字符串

1
2
3
4
5
6
7
8
// 包含年月日时分秒
var date = new Date();
// 包含年于日时分秒
var str1 = date.toLocalString();
// 包含年月日
var str2 = date.toLocalDateString();
// 包含时分秒
var str3 = date.toLocalTimeString();

Date 对象间的运算

两个时间对象相减,得到的时两个对象间相差的毫秒数