Date and time
JavaScript Date and Time (JavaScript日期和时间)
In JavaScript, there is a built-in object Date for handling all the date and time related operations. For instance, you can use it for displaying the current date and time, creating a calendar, build a timer, and much more. (在JavaScript中,有一个内置对象Date ,用于处理所有与日期和时间相关的操作。例如,您可以使用它来显示当前日期和时间、创建日历、构建计时器等。)
How to Create a Date Object
How to Create a Date Object (如何创建Date对象)
To learn how to create a new Date object, follow the steps below. (要了解如何创建新的Date对象,请按照以下步骤操作。)
Note that the new operator is generally used to create a date object. (请注意,新运算符通常用于创建日期对象。)
Call new Date () choosing one of the following arguments:
new Date()
You can create a Date object for the current date and time without arguments like this:
let nowDate = new Date();
console.log(nowDate); // shows current date/time
This action returns the current date with the time and time zone. (此操作返回当前日期以及时间和时区。)
We can distinguish other ways of creating a Date using the new operator. (我们可以使用新运算符区分创建日期的其他方法。)
New Date with Milliseconds
New Date with Milliseconds (以毫秒为单位的新日期)
Creating a Date object with the time equal to the number of milliseconds passed after the January 1st, 1970 UTC+0. (创建Date对象,其时间等于1970年1月1日UTC +0之后经过的毫秒数。)
Here is an example:
// 0 means 01.01.1970 UTC+0
let startDate = new Date(0);
console.log(startDate);
// now add 24 hours, get 02.01.1970 UTC+0
let startTime = new Date(24 * 3600 * 1000);
console.log(startTime);
In this example, a timestamp is used to represent the number of milliseconds passed since the beginning of 1970. (在此示例中,时间戳用于表示自1970年初以来传递的毫秒数。)
Creating Date Object Using dateString
Creating Date Object Using dateString (使用dateString创建Date对象)
It is possible to create a Date object by passing the date string representation. The string representation will be accepted in case it can be parsed using Date.parse(). (可以通过传递日期字符串表示来创建Date对象。如果可以使用Date.parse ()进行解析,则将接受字符串表示形式。)
Here is an example:
let date = new Date("2019-12-26");
console.log(date);
//The isn't a fixed time, so it's expected to be midnight GMT and
// is modified according to the timezone, in which the code is run
// So the result could be
// Thu Dec 26 2019 04:00:00 GMT+1100 (Australian Eastern Daylight Time)
The following format is acceptable: new Date(year, month, date, hours, minutes, seconds, ms). You should also follow these rules:
The year should consist of four digits ( for example, 2020);
The counting of the month must start from 0 (For example, 0 is January and 11 is December);
The day of the month is the date parameter; if it is absent, you should assume 1.
In case hours/minutes/seconds/ms is absent, you should assume them to be equal 0. (-如果缺少小时/分钟/秒/毫秒,则应假定它们等于0。)
For example:
new Date(2019, 0, 1, 0, 0, 0, 0); // 1 Jan 2019, 00:00:00
new Date(2019, 0, 1); // the same, hours etc are 0 by default
Minimal precision should be one millisecond. (最小精度应为1毫秒。)
For instance:
let date = new Date(2019, 1, 1, 2, 3, 4, 567);
console.log(date);
Accessing Date Components
Accessing Date Components (访问日期组件)
Now, we will discover the ways of accessing data components. Here they are:
getFullYear()
getting the year ( should be of 4 digits). (获取年份(应为4位数字)。)
getMonth()
getting the month ( from 0 to 11). (获取月份(从0到11 )。)
getDate()
getting the day of a month ( from 1 to 31). (获取一个月的日期(从1到31 )。)
getHours(),
getMinutes(),
(getMinutes (),)
getSeconds(),
(getSeconds (),)
getMilliseconds()
getting the appropriate time components. (获取适当的时间分量。)
It is essential to use getFullYear(), not getYear(), as the latter deprecated and can return 2-digit year at times. So, you’d better never use it in your practice. (必须使用getFullYear () ,而不是getYear () ,因为后者已弃用,有时可以返回2位数的年份。所以,你最好不要在练习中使用它。)
Besides, it is possible even to get a weekday by calling:
getDay()
It will allow you to get a weekday from Sunday 0 to Saturday 6. (它将允许您从周日0到周六6的工作日。)
How to Set Date Components
How to Set Date Components (如何设置日期组件)
In JavaScript, several methods are used for setting the date and time components. Among them are:
setFullYear(year, [month], [date])
setMonth(month, [date])
setDate(date)
setHours(hour, [min], [sec], [ms])
setMinutes(min, [sec], [ms])
Some methods are capable of setting multiple components simultaneously. For instance, setHours. (有些方法能够同时设置多个组件。例如, setHours。)
Here is an example:
let today = new Date();
today.setHours(0);
console.log(today); // still today, but the hour is changed to 0
today.setHours(0, 0, 0, 0);
console.log(today); // still today, now 00:00:00 sharp.
Autocorrection
Autocorrection (自动校正)
A handy feature of Date objects is autocorrection. You can set values that are out of range, and it will adjust them automatically. (Date对象的一个方便功能是自动校正。您可以设置超出范围的值,它将自动调整它们。)
For example:
let date = new Date(2019, 8, 32); // 32 Sep 2019
console.log(date);
Date to Number, Date Diff
Date to Number, Date Diff (日期至数字,日期差异)
Whenever you convert a Date to number, it is transformed into the timestamp, like date.getTime(). (每当将Date转换为数字时,它都会转换为时间戳,如date.getTime ()。)
Let’s consider the following example:
let msDate = new Date();
console.log(+msDate); // it's a same as date.getTime(), it's the number of milliseconds
It is also important to note that dates can be subtracted. You can use it for measurements, as follows:
let startDate = new Date(); // start measuring time
for (let x = 0; x < 10000; x++) {
let smth = x * x * x;
}
let endDate = new Date(); // end measuring time
console.log(`The loop took ${endDate - startDate} ms`);
Date.now()
Date.now() (日期:现在)
If you decide to measure time, it is not necessary to use the Date object. You can use Date.now(), which will return the current timestamp. (如果您决定测量时间,则无需使用Date对象。您可以使用Date.now () ,它将返回当前时间戳。)
For instance:
let startDate = Date.now(); // milliseconds count from 1 Jan 1970
for (let x = 0; x < 10000; x++) {
let doSomething = x * x * x;
}
let endDate = Date.now();
console.log(`The loop took ${endDate - startDate} ms`);
Date.parse From a String
Date.parse From a String (Date.parse来自字符串)
If you want to read a date from a string, the Date.parse(str) will help you. The format of the string must be: MM-DDTHH:mm:ss.sssZ. Several shorter options are also possible: YYYY-MM-DD or YYYY-MM or even YYYY.
Here is an example of the usage of Date.parse(str):
let ms = Date.parse('2019-02-28T14:52:20.254-08:00');
console.log(ms); // 1551394340254, it’s a timestamp
A new Date can be instantly created from the timestamp, like this:
let date = new Date(Date.parse('2019-02-28T14:52:20.254-08:00'));
console.log(date);
Summary
Summary (概要)
In JavaScript, the Date object is used for representing date and time. The Date object includes both of them. As a rule, the months are counted starting from zero and ending with 11. The weekdays are also counted starting from zero. In JavaScript, the dates might be subtracted and give their difference in milliseconds, as a Date is transformed into timestamp when converted to a number. Finally, unlike other systems, in JavaScript, timestamps are in milliseconds, not seconds.