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.
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.
|
|
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.
|
|
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.
|
|
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.
|
|
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.
|
|
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.
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.
2.2. Date and time acquisition
Date object can get the various parts of the date and time by many methods, such as
|
|
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.
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.
|
|
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.
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.
|
|
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.
|
|
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.
|
|
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.
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.
2.8. Other related points of knowledge
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 thegetDay()
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.