# Timezones
- Local time;
- UTC(Universal time coordinated) is Greenwich Mean Time(GMT);
JS 日期方法返回的日期默认都是 local time; 除非你声明要获取 UTC
# Creating a date
const dateExample = new Date();
Four possible ways to use new Date();
- With a date-string: (don't create dates with date strings.)
- new Date('1988-03-21')
- ISO 8601 Extended format:
YYYY-MM-DDTHH:mm:ss:sssZ
- T: the start of time;
- Z: present, data => UTC; NOT present => Local Time;
- With date arguments:(Recommended)
- Local Time: new Date(2019, 5, 11, 5, 23, 59);
- Month is zero-indexed. ⏫ 月份 5 => June;
- UTC Time: new Date(Date.UTC(2019, 5, 11));
- With a timestamp
- Timestamp: 毫秒 1970.01.01;
- new Date(1560211200000);
- With no arguments
- new Date();
# Formatting a date
# Writing a custom date format
- getFullYear
- getMonth: 0~11
const months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December',
];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
- getDate: 1~31
- getDay: 0~6
const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
1
- getHours: 0~23
- getMinutes: 0~59
- getSeconds: 0~59
- getMilliseconds: 0~59
# Comparing dates
- with >, <, >= and <=.
const earlier = new Date(2019, 0, 26);
const later = new Date(2019, 0, 27);
console.log(earlier < later); // true
1
2
3
4
2
3
4
- can't compared them with == or ===. Use getTime()
const a = new Date(2019, 0, 26);
const b = new Date(2019, 0, 26);
console.log(a == b); // false
console.log(a === b); // false
const isSameTime = (a, b) => {
return a.getTime() === b.getTime();
};
const a = new Date(2019, 0, 26);
const b = new Date(2019, 0, 26);
console.log(isSameTime(a, b)); // true
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# Getting a date from another date
Setter methods mutate the original date object. Use them on a new date.
- setFullYear
- setMonth
- setDate
- setHours
- setMinutes
- setSeconds
- setMilliseconds
const d = new Date(2019, 0, 10);
d.setDate(15);
console.log(d); // 15 January 2019
1
2
3
4
2
3
4
# Adding/Subtracting delta from another date
// 1. The first approach
const today = new Date(2019, 2, 28);
const finalDate = new Date(today);
finalDate.setDate(today.getDate() + 3);
console.log(finalDate); // 31 March 2019
// 2. The second approach
const today = new Date(2019, 2, 28);
// Getting required values
const year = today.getFullYear();
const month = today.getMonh();
const day = today.getDate();
// Creating a new Date (with the delta)
const finalDate = new Date(year, month, day + 3);
console.log(finalDate); // 31 March 2019
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# Automatic date correction
JS recalculate the date which is ourside of its acceptable range automatically.