Post Link (opens new window)

# Timezones

  1. Local time;
  2. 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();

  1. With a date-string: (don't create dates with date strings.)
    1. new Date('1988-03-21')
    2. ISO 8601 Extended format: YYYY-MM-DDTHH:mm:ss:sssZ
      1. T: the start of time;
      2. Z: present, data => UTC; NOT present => Local Time;
  2. With date arguments:(Recommended)
    1. Local Time: new Date(2019, 5, 11, 5, 23, 59);
    2. Month is zero-indexed. ⏫ 月份 5 => June;
    3. UTC Time: new Date(Date.UTC(2019, 5, 11));
  3. With a timestamp
    1. Timestamp: 毫秒 1970.01.01;
    2. new Date(1560211200000);
  4. With no arguments
    1. new Date();

# Formatting a date

# Writing a custom date format

  1. getFullYear
  2. 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
  1. getDate: 1~31
  2. getDay: 0~6
const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
1
  1. getHours: 0~23
  2. getMinutes: 0~59
  3. getSeconds: 0~59
  4. getMilliseconds: 0~59

# Comparing dates

  1. 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
  1. 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

# Getting a date from another date

Setter methods mutate the original date object. Use them on a new date.

  1. setFullYear
  2. setMonth
  3. setDate
  4. setHours
  5. setMinutes
  6. setSeconds
  7. setMilliseconds
const d = new Date(2019, 0, 10);
d.setDate(15);

console.log(d); // 15 January 2019
1
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

# Automatic date correction

JS recalculate the date which is ourside of its acceptable range automatically.

Last Updated: 2/8/2023, 2:30:06 AM