1. Date and time formatting

1.1. Native methods

1.1.1 Using the toLocaleString method

The Date object has a toLocaleString method that formats the datetime according to the local time and locale settings. For example.

1
2
3
const date = new Date();
console.log(date.toLocaleString('en-US', { timeZone: 'America/New_York' })); // 2/16/2023, 8:25:05 AM
console.log(date.toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' })); // 2023/2/16 上午8:25:05

The toLocaleString method accepts two parameters, the first one is the locale setting and the second one is an option to specify the date time format and time zone information

1.1.2. Using the Intl.DateTimeFormat object

The Intl.DateTimeFormat object is a constructor for formatting dates and times. You can use this object to generate an instance of a formatted date and time, and set the date and time format and time zone as needed. Example.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
const date = new Date();
const formatter = new Intl.DateTimeFormat('en-US', {
  timeZone: 'America/New_York',
  year: 'numeric',
  month: 'numeric',
  day: 'numeric',
  hour: 'numeric',
  minute: 'numeric',
  second: 'numeric',
});
console.log(formatter.format(date)); // 2/16/2023, 8:25:05 AM

You can specify the desired date and time format in the options, including year, month, day, hour, minute, second, etc. Time zone information can also be set.

1.2. Use string template

String templates can be used to format the date and time into a specific format string. For example.

1
2
3
4
5
6
7
8
const date = new Date();
const year = date.getFullYear().toString().padStart(4, '0');
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const day = date.getDate().toString().padStart(2, '0');
const hour = date.getHours().toString().padStart(2, '0');
const minute = date.getMinutes().toString().padStart(2, '0');
const second = date.getSeconds().toString().padStart(2, '0');
console.log(`${year}-${month}-${day} ${hour}:${minute}:${second}`); // 2023-02-16 08:25:05

The above code uses a string template to format the datetime as YYYY-MM-DD HH:mm:ss. You can modify the format according to your actual needs.

1.3. Custom formatting functions

1.3.1. Formatting functions that cannot specify a format

can write a custom function to format the date and time. For example.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
function formatDateTime(date) {
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();
  return `${year}-${pad(month)}-${pad(day)} ${pad(hour)}:${pad(minute)}:${pad(second)}`;
}

function pad(num) {
  return num.toString().padStart(2, '0');
}

const date = new Date();
console.log(formatDateTime(date)); // 2023-02-16 08:25:05

The above code defines a formatDateTime function and a pad function to format the datetime and fill in the numbers. The format can be modified as needed, so it is less generic.

1.3.2. Formatting functions that can specify the format

The following is an example of a highly versatile custom date-time formatting function.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
function formatDateTime(date, format) {
  const o = {
    'M+': date.getMonth() + 1, // Month
    'd+': date.getDate(), // Day
    'h+': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12, // Hours
    'H+': date.getHours(), // Hours
    'm+': date.getMinutes(), // Minutes
    's+': date.getSeconds(), // seconds
    'q+': Math.floor((date.getMonth() + 3) / 3), // Quarterly
    S: date.getMilliseconds(), // 毫秒
    a: date.getHours() < 12 ? '上午' : '下午', // A.M./P.M.
    A: date.getHours() < 12 ? 'AM' : 'PM', // AM/PM
  };
  if (/(y+)/.test(format)) {
    format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
  }
  for (let k in o) {
    if (new RegExp('(' + k + ')').test(format)) {
      format = format.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
      );
    }
  }
  return format;
}

This function accepts two parameters, the first parameter is the datetime to be formatted, which can be a Date object or a string representing the datetime, and the second parameter is the format to be formatted, such as yyyy-MM-dd HH:mm:ss. This function will format the datetime to the specified format and return the formatted string.

This function uses a regular expression to match the placeholders in the format string and then replaces the placeholders according to the corresponding date-time values. Where y will be replaced with the year, and M, d, h, H, m, s, q, S, a, and A denote the month, date, hour (12-hour), hour (24-hour), minute, second, quarter, millisecond, AM/PM, and AM/PM, respectively.

An example of using this function for date time formatting is as follows.

1
2
3
4
5
const date = new Date();
console.log(formatDateTime(date, 'yyyy-MM-dd HH:mm:ss')); // 2023-02-16 08:25:05
console.log(formatDateTime(date, 'yyyy年MM月dd日 HH:mm:ss')); // 2023年02月16日 08:25:05
console.log(formatDateTime(date, 'yyyy-MM-dd HH:mm:ss S')); // 2023-02-16 08:25:05 950
console.log(formatDateTime(date, 'yyyy-MM-dd hh:mm:ss A')); // 2023-02-16 08:25:05 上午

The formatting can be modified according to actual needs, as well as supporting more placeholders and formatting options.

1.4. Use third-party libraries

In addition to the native methods, there are many third-party libraries that can be used to format datetime, such as Moment.js and date-fns. These libraries provide more datetime formatting options and are compatible with different browsers and environments.

1
2
3
const date = new Date();
console.log(moment(date).format('YYYY-MM-DD HH:mm:ss')); // 2023-02-16 08:25:05
console.log(dateFns.format(date, 'yyyy-MM-dd HH:mm:ss')); // 2023-02-16 08:25:05

The above are several commonly used date-time formatting methods. When formatting date-time, you can use native methods, custom functions or third-party libraries, and choose the appropriate method to format according to your actual needs.

2. Other common methods of date and time

2.1. Create Date object

To create a Date object, you can use new Date(), without passing any parameters, the current time will be used. You can also pass in a date string or a number of milliseconds, for example.

1
2
3
const now = new Date(); // Current Time
const date1 = new Date("2022-01-01"); // String for the specified date
const date2 = new Date(1640995200000); // Specify milliseconds

2.2. Date and time acquisition

Date object can get the various parts of the date and time by many methods, such as

1
2
3
4
5
6
7
8
9
const date = new Date();
const year = date.getFullYear(); // Year, e.g. 2023
const month = date.getMonth(); // Month, 0-11, 0 for January, 11 for December
const day = date.getDate(); // Date, 1-31
const hour = date.getHours(); // Hours, 0-23
const minute = date.getMinutes(); // Minutes, 0-59
const second = date.getSeconds(); // Seconds, 0-59
const millisecond = date.getMilliseconds(); // Milliseconds, 0-999
const weekday = date.getDay(); // Day of the week, 0-6, 0 means Sunday, 6 means Saturday

2.3. Date and time calculation

You can use the set method of Date object to set the various parts of date and time, or you can use the get method to get the various parts of date and time, and then calculate them. For example, to calculate the number of days between two dates, you can first convert the two dates into milliseconds, then calculate the difference value between them, and finally convert the difference value into days, for example.

1
2
3
4
const date1 = new Date("2022-01-01");
const date2 = new Date("2023-02-16");
const diff = date2.getTime() - date1.getTime(); // Milliseconds
const days = diff / (1000 * 60 * 60 * 24); // Days

2.4. date and time comparison

You can use the getTime() method of the Date object to convert a date to milliseconds and then compare the millisecond sizes of the two dates to determine their order. For example, to compare the order of two dates, you can convert them to milliseconds and then compare their sizes, e.g.

1
2
3
4
5
6
7
8
9
const date1 = new Date("2022-01-01");
const date2 = new Date("2023-02-16");
if (date1.getTime() < date2.getTime()) {
  console.log("date1 before date2");
} else if (date1.getTime() > date2.getTime()) {
  console.log("date1 after date2");
} else {
  console.log("date1 and date2 are equal");
}

2.5. date and time operations

You can use some methods of Date object to perform date and time operations, for example, set the date using setDate() method, set the hours using setHours() method, set the milliseconds using setTime() method, and so on. For example, to add a day to the date, you can use the setDate() method, e.g.

1
2
3
const date = new Date();
date.setDate(date.getDate() + 1); // Add a day
console.log(date.toLocaleDateString());

2.6. Get the start and end times of last week, this week, last month, and this month

The following is a JavaScript code example to get the start and end time of this week, last week, this month and last month.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// Get the start time and end time of the week
function getThisWeek() {
  const now = new Date();
  const day = now.getDay() === 0 ? 7 : now.getDay(); // Convert Sunday to 7
  const weekStart = new Date(now.getFullYear(), now.getMonth(), now.getDate() - day + 1);
  const weekEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate() + (6 - day) + 1);
  return { start: weekStart, end: weekEnd };
}

// Get the start time and end time of the last week
function getLastWeek() {
  const now = new Date();
  const day = now.getDay() === 0 ? 7 : now.getDay(); // Convert Sunday to 7
  const weekStart = new Date(now.getFullYear(), now.getMonth(), now.getDate() - day - 6);
  const weekEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate() - day);
  return { start: weekStart, end: weekEnd };
}

// Get the start time and end time of the month
function getThisMonth() {
  const now = new Date();
  const monthStart = new Date(now.getFullYear(), now.getMonth(), 1);
  const monthEnd = new Date(now.getFullYear(), now.getMonth() + 1, 0);
  return { start: monthStart, end: monthEnd };
}

// Get the start time and end time of the previous month
function getLastMonth() {
  const now = new Date();
  const monthStart = new Date(now.getFullYear(), now.getMonth() - 1, 1);
  const monthEnd = new Date(now.getFullYear(), now.getMonth(), 0);
  return { start: monthStart, end: monthEnd };
}

In the above code, the getThisWeek(), getLastWeek(), getThisMonth() and getLastMonth() functions return the start and end times of this week, last week, this month and last month, respectively, for the current time. These functions use the methods of the Date object, such as getFullYear(), getMonth() and getDate(). They can be used to get scenarios that require time interval calculations, such as counting data within a certain time range, etc.

Examples of using these functions to get time intervals.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
const thisWeek = getThisWeek();
console.log(thisWeek.start); // Start time of the week
console.log(thisWeek.end); // End of the week

const lastWeek = getLastWeek();
console.log(lastWeek.start); // Last week's start time
console.log(lastWeek.end); // Last week's end time

const thisMonth = getThisMonth();
console.log(thisMonth.start); // Start time of the month
console.log(thisMonth.end); // End of the month

const lastMonth = getLastMonth();
console.log(lastMonth.start); // Last month's start time
console.log(lastMonth.end); // Last month's end time

Using these functions it is easy to obtain the desired time interval and perform subsequent operations.

2.7. Calculating age based on date of birth

The following is a code example for calculating age based on date of birth, including the treatment of leap years.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
function calculateAge(birthDate) {
  const birthYear = birthDate.getFullYear();
  const birthMonth = birthDate.getMonth();
  const birthDay = birthDate.getDate();
  const now = new Date();
  let age = now.getFullYear() - birthYear;
  
  if (now.getMonth() < birthMonth || (now.getMonth() === birthMonth && now.getDate() < birthDay)) {
    age--;
  }
  
  // Check for leap years
  const isLeapYear = (year) => (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  const isBirthLeapYear = isLeapYear(birthYear);
  
  // Adjusting the age for leap years
  if (isBirthLeapYear && birthMonth > 1) {
    age--;
  }
  
  if (isLeapYear(now.getFullYear()) && now.getMonth() < 1) {
    age--;
  }
  
  return age;
}

This function takes a Date object as a parameter, representing the date of birth. This function calculates the time difference between the current date and the date of birth to determine the age. Among other things, it uses the getFullYear(), getMonth(), and getDate() methods of the Date object to get the year, month, and day of the date of birth. The age is calculated using the year, month, and day of the current date. If the current month is less than the birth month, or if the current month is equal to the birth month but the current date is less than the birth date, the age is subtracted by one. In this function, an isLeapYear() function is defined to check if the given year is a leap year. Then, when calculating the age, this function is called to check if the year of birth and the current year are leap years. If the birth year is a leap year and the birth month is on or after February, the age is subtracted by one. If the current year is a leap year and the current month is on or before January, the age is subtracted by one. This allows you to correctly calculate the age for birth dates that contain a leap year.

This method of calculating age is based only on the time difference between the current date and the date of birth, and does not take into account the specific month and day. Therefore, for people whose birthdays have not yet arrived, the calculated age will be one year younger than the actual age.

An example of using this function to calculate age.

1
2
3
const birthDate = new Date("1990-01-01");
const age = calculateAge(birthDate);
console.log(age); // 33

In the above code, a Date object is constructed, which represents the date of birth. Then the calculateAge() function is called, passing the date of birth as an argument. The function returns the time difference between the current date and the date of birth to determine the age. Finally, the calculated age is printed.

When using the Date object, the following points need to be noted.

  • The month starts from 0, with 0 indicating January and 11 indicating December.
  • The getDate() method returns the date, while the getDay() method returns the day of the week.
  • The year of a Date object is a full four-digit number, such as 2023.
  • When you create a Date object with new Date(), it returns the time in the current time zone. If you need to use UTC time, you can use new Date(Date.UTC()).

The Date object in JavaScript provides a number of methods and properties that can be used to work with dates and times, choosing the appropriate method and technique for each situation.