1 Background and basic concepts
In the past, different parts of the world had their own local time. For example, in ancient China, a day and night were divided into twelve hours, and each hour was equivalent to two modern hours. But with the development of transportation and communication, the exchanges between different places become more and more frequent, and the different local time has caused a lot of trouble to people. And in 1884 the international conference on longitude established global standards, determine the Greenwich in London area of this place as the starting point of zero meridian (prime meridian), and with the earth rotates once every 24 hours from west to east 360 °, the regulation of longitude every 15 °, 1 hour time difference, and every 15 ° meridian is called the time zone of the central meridian. The world is divided into 24 time zones, including 23 whole time zones and two half time zones on the left and right sides of the 180° longitude. The eastern longitude is earlier than the western longitude, that is, if Greenwich mean time is 12 noon, the central longitude 15°E is 1 p.m. and the central longitude 30°E is 2 p.m. Conversely, the time zone for the 15°W central longitude is 11 am and the time zone for the 30°W central longitude is 10 am. If two people were traveling east and west from 0° Greenwich at the same time, they would be 24 hours apart when they were at 180° of longitude, so the 180° of longitude is designated as the international day of change, subtracting one day from west to east and adding one day from east to west.
1.1 Standard time
- GMTGreenwich Mean Time (Greenwich Mean TimeThe worldIs an astronomical concept
- In the 17th century, the Royal Observatory in Greenwich conducted celestial observations for the expansion of maritime supremacy. In 1675 the Royal Observatory in Greenwich was established. Then in 1884 the International Longitude Conference decided to use the meridian through Greenwich as the longitude zero dividing the eastern and western hemispheres of the earth. A 24-hour clock on the wall at the entrance to the observatory shows the current time, which is the world reference point for global time, which is based on Greenwich Mean Time. In fact, universal time is not accurate. Greenwich is at its highest point when the sun passes over the Greenwich Observatory at 12 noon, but the earth’s rotation actually slows down every year, by a few tenths of a second.
- International Atomic Time (IAT). In the international measurement system, time is one of the seven basic quantities, and Greenwich time, which is based on astronomy, certainly cannot meet the needs of scientific accuracy. As a result, atomic clocks were invented, using the frequency of the electromagnetic wave emitted by electrons within atoms as they jump between energy levels to determine the length of a second. GMT differs from IAT by about 0.9 seconds per year, mainly due to the irregular rotation of the Earth and tidal effects.
- UTC(Universal Time Coordinated), i.eCoordinated universal timeIs a version of universal time used to correct GMT
- UTC is actuarial time combined with mean solar time (based on Greenwich Mean Time (GMT), a new time scale corrected for the motion of the Earth’s axis, and International Atomic time in seconds. UTC and GMT are generally considered equal.
- A leap second, or jump second, is a UTC adjustment of one second plus or minus GMT. IAT has an accuracy of several nanoseconds per day, while universal time has an accuracy of several milliseconds per day. To ensure that the difference between UTC and UTC is not greater than 0.9 seconds, a full second plus or minus is added to UTC if necessary. This technical measure is called a leap second. There are two scientific systems for measuring time: “World time,” based on astronomical measurements of the Earth’s rotation, and “atomic time,” based on periods of atomic oscillation. While “universal time” varies due to the instability of the Earth’s rotation (caused by the uneven distribution of material on earth and perturbations of other planets, etc.), “atomic time” (a more constant system of time derived from atomic clocks) is relatively constant. The difference in the rates of the two time scales, which typically takes about one second to two years, has been positive 16 leap seconds since January 1980 (November 2012), as shown below:
1.2 the time zone
- Local time, UTC+ Time zone. Convert UTC or GMT to LT: LT=UTC+ time zone difference. East is the corresponding time zone difference plus, west is the time zone difference minus. If Beijing is district 8 east, Beijing time =UTC+8
- DST, daylight saving time. It’s when the sun rises early in the summer and clocks are moved forward an hour to get the sun’s rays in. Major countries in Europe and the United States have cited this practice. If DST=UTC+ Time zone +1
Time representation in computer
In the old Unix operating system, time was stored as a 32-bit signed number. The maximum interval between 32 bits of TIME is 68 years, and the earliest UNIX operating system takes into account the age of computer generation and application TIME as the epoch of UNIX TIME (start TIME) on January 1, 1970, and takes 1970 as the middle point. Both left and right shifts can be taken into account earlier or later, so 0 o ‘clock on January 1, 1970 is used as the origin of the computer’s representation of time, and the number of seconds that have passed since January 1, 1970 is stored as a 32-bit integer. This time (00:00:00 on January 1, 1970) was used as the zero point of time. This efficient and concise time representation is called the “Unix time era “.
2.1 the timestamp
- Unix time (stamp), the number of seconds from the current time to 00:00:00 UTC, January 1, 1970.
- Time stamp, showing the number of milliseconds from the current time to 00:00:00 UTC, January 1, 1970.
2.2 Questions for 2038
Unix timestamps are the number of seconds that have elapsed since January 1, 1970 (midnight UTC/GMT), excluding leap seconds. On a 32-bit system, the maximum value of time_t is 0x7FFFFFFFF. If the maximum value of time_t is set to 2001-19 03:14:07, the system time is 2038-01-19 03:14:07. If time_T is set to a maximum value, the system time will overflow into a negative value and the system time will go back to 1901. Then the operating system and the upper software will run wrong.
The simplest and most crude way to solve this problem is to represent the time in 64 bits. The maximum 64-bit time is 292,277,026,596, 15:30:08, Sunday (UTC) (292,277,026,596, 23:30:08, Beijing time). In fact, most 64-bit operating systems have changed time_t to a 64-bit integer, and for these machines the problem will be gone in 2038. For embedded devices, however, there are still plenty of 32-bit systems running around the world, and there is no guarantee that they will be retired before 2038. In addition, for 64-bit operating systems running 32-bit applications, the same 2038 problem will occur.
2.3 Two international time standards: ISO8601 and RFC2822
ISO8601, known as “data storage and exchange forms, information exchange, date and time representation”, provides the international standard date and time representation.
- Use only numbers as the basic format. Use a dash “-” to separate the year, month, and day in extended format.
- Each date and time value has a fixed number of digits that must be filled with leading zeros.
- The date and time can contain only digits or a few special characters (for example, “-“, “:”, “T”, “W”, and “Z”). Local characters such as “January” and “Thursday” are not allowed.
- ISO 8601 uses a 24-hour system. HH: MM: SSS. SSS, HH: MM: SS, HH: MM, HH: MM. HH indicates the compliance time format.
- Separate the date and time with the letter T. Such as
20180703T224426Z
或2018-07-03T22:44:26Z
。
RFC2822: Internet message format for unifying dates and times in HTTP and E-mail headers. RFC 2822 includes the day of the week (short), numeric date, three-letter abbreviation of the month, year, time, and time zone, displayed asWed 01 Jun 2016 14:31:46 -0700
3 Time representation in the front end
The back end typically returns the number of seconds or milliseconds of time, while the display in the front page may vary. It may be:
- The 2021-1-25
- 2021/1/25
- January 25, 2021
- January 25, 2021 12:35:10
- At 12:35 minutes and 10 seconds on January 25, 2021
- .
In javascipt, time processing needs to use the built-in object Date
- The constructor
var now = new Date();
To obtainThe current timeConstruct the Date object. Date objects can be constructed in any of the following ways
new Date("month dd,yyyy hh:mm:ss"); new Date("January 1,2020 22:10:35");
new Date("month dd,yyyy"); new Date("Three out of 12201");
new Date(yyyy,mth,dd,hh,mm,ss); new Date(2006.0.12.22.19.35);
new Date(yyyy,mth,dd); new Date(2008.3.27);
new Date(ms); new Date(1234567890000);
Copy the code
- Date.parse()
Var someDate = new Date(date.parse (‘May 25,2004’)); Parse () returns NaN if the string passed to the data.parse () method does not represent the date format. In fact, if you pass a string representing a Date directly to the Date constructor, the date.parse () method is also called behind the scenes.
- Date.now() gets the current timestamp
Date.now() can be used to count the running time of the program
// Get the start time
var start = Date.now();
// Call the function
dosomething();
// Get the end time
var stop = Date.now(),
Copy the code
- Like other reference types, the Date type overrides the toLocaleString(), toString(), and valueOf() methods.
Instead of a string, the valueOf() method returns the millisecond timestamp of the date. This makes it easy to compare date values using the comparison operator (greater than or less than).
let date=new Date()
date.toString() "Tue Jan 26 2021 18:24:40 GMT+0800"
date.toDateString() "Tue Jan 26 2021"
date.toGMTString() "Tue, 26 Jan 2021 10:24:40 GMT"
date.toUTCString() "Tue, 26 Jan 2021 10:24:40 GMT"
date.toISOString() "The 2021-01-26 T10:24:40. 224 z"
date.toJSON() "The 2021-01-26 T10:24:40. 224 z"
date.toLocaleString() "6:24:40 2021/1/26 afternoon"
date.toLocaleTimeString() "Afternoon 6:24:40"
date.toLocaleDateString() "2021/1/26"
Copy the code
- Get and set
let date=new Date(a); Date. GetFullYear () - to get4Digit year date.getMonth() - Gets the month, value0~11.0The corresponding1Month date.getday () - Gets the day of the week0~6.0On Sunday,1On Monday,6Date.getdate () - Gets the value of the day in a month1~31.1namely1No.,31namely31Date.gethours () - Obtains the number of hours0~23Date.getminutes () - Gets the number of minutes0~59Date.getseconds () - Gets the number of seconds0~59Date.getmilliseconds () - Gets the number of milliseconds0~999Date. GetTime () - returns1970years1month1The number of milliseconds from day to current timeDateObjects also have corresponding UTC methods, including getUTC and setUTC >new Date().getHours()
21
> new Date().getUTCHours()
13
Copy the code
3.1 Common Time Processing Scenarios
JS determine how many days there are in x year x month
New Date(” XXXX /xx/xx”); new Date(” XXXX /xx/xx”); new Date(” XXXX /xx/xx”); If you pass 2019/12/0″(note that month starts at 0), you get “2018/12/31”. And the big advantage is that when you pass in “XXXX /3/0”, you get the last day of February XXXX, and it automatically checks whether that year is a leap year and returns 28 or 29, so you don’t have to decide for yourself. So, if we want to know how many days there are in a month and a year, we just need to pass the month to next month and the Date to 0 when constructing the Date function, so that we can get the Date object of the last day of the month
function getDaysInMonth(year,month){
let temp = new Date(year,month,0);
return temp.getDate();
}
getDaysInMonth(2019.2) / / 28
getDaysInMonth(2020.2) / / 29
Copy the code
JS generates a countdown date of 7 days
For example, if today is October 1, the generated array is [” September 25 “,” September 26 “,” September 27 “,” September 28 “,” September 29 “,” September 30 “,” October 1 “]. The difficulty is determining whether the month (or month) has 30 days or 31, and it is possible to have 29 days in February
let now = new Date(a);let s = ' ';
let i = 0;
while (i < 7) {
s += now.getFullYear() + '/' + (now.getMonth() + 1) + '/' + now.getDate() + '\n';
now = new Date(now - 24 * 60 * 60 * 1000);
i++;
}
console.log(s);
Copy the code
JS format function
// An extension to Date that converts Date to a String of the specified format
// Month (M), day (d), hour (h), minute (M), second (s), quarter (q) can use 1 or 2 placeholders,
// Year (y) can use 1-4 placeholders, millisecond (S) can only use 1 placeholder (1-3 digits)
/ / example:
/ / (new Date ()). The Format (" YYYY - MM - DD HH: MM: ss. S ") = = > 2006-07-02 08:09:04. 423
/ / (new Date ()). The Format (" YYYY - M - D H: M: s.S ") = = > 2006-7-2 8:9:4. 18
Date.prototype.Format = function (fmt) {
const o = {
"M+": this.getMonth() + 1./ / in
"D+": this.getDate(), / /,
"H+": this.getHours(), / / hour
"m+": this.getMinutes(), / / points
"s+": this.getSeconds(), / / SEC.
"q+": Math.floor((this.getMonth() + 3) / 3), / / quarter
"S": this.getMilliseconds() / / ms
};
if (/(Y+)/.test(fmt)){
fmt = fmt.replace(RegExp. $1,this.getFullYear() + "").substr(4 - RegExp.$1.length));
}
for (const k in o){
if (new RegExp("(" + k + ")").test(fmt)){
fmt = fmt.replace(RegExp. $1,RegExp.$1.length == 1)? (o[k]) : (("00" + o[k]).substr((""+ o[k]).length))); }}return fmt;
}
let date=new Date(a); date.Format("YYYY-MM-DD HH:mm:ss");
Copy the code
3.2 Practical time processing libraries -moment, dayjs, Miment
All three of these libraries are very useful JS time processing libraries, and all three libraries are very easy to use, even the use of the API is highly consistent, the latter two borrowed from moment. Dayjs and Miment can basically replace moment in daily time processing.
moment | dayjs | miment | |
---|---|---|---|
Github stars | 45k | 33k | 332 |
The size of the | 200kb | 2kb | 1kb |
variability | is | no | is |
Support extended | no | is | no |
Methods the number of | more | less | less |
Whether the maintenance | no | is | is |
Here’s the moment’s official statement:
“Moment.js has announced that it is shutting down development and going into maintenance. This is a large and comprehensive time and date library that makes it very easy to calculate times and dates in JavaScript. It has been downloaded over 12 million times per week and has been successfully used in millions of projects. However, as an old star project born in 2011, moment.js is not without its flaws, and officials have summed up two problems:
3.2.1 Mutable Objects
A Moment object is a mutable object; simply put, any addition or subtraction at any time, including operations such as startOf(), changes itself. This design makes the code very uncontrollable, and it is easy to introduce all kinds of hidden and difficult to debug bugs. So much so that we need to call.clone() once before each step of modification.
3.2.2 The package size is too Large
Because momnet.js packs all the functionality and supported languages into a single package, the size of the package is an exaggerated 280.9KB, and it’s not shaking for Tree. If you want to use time zone specific features, the package size is 467.6 kB. To put it simply, we might just need a.format method to format time, and users would need to load hundreds of kilobytes of libraries, which is not cost-effective.” Officials offer three alternatives:
- Do not use the library
For some simple time processing needs, in fact, JavaScript Date and Intl objects can be satisfied. The powerful Intl object displays date and time formats in different time zones and languages, and is already well supported on most modern browsers.
- Temporal
There may come a time when we don’t need any libraries anymore. Temporal is seen as the new built-in time and date scheme of the future and Temporal is something to look forward to. The ECMA TC39 interim proposal is working to write a better date and time API for the JavaScript language. It is currently in phase 2 of the TC39 process. This is a redesigned time and date API built into the JS language that you can now try Temporal with experimental polyfills, but it is still a long way from being available on a large scale in production.
- Alternative libraries
3.2.3 DayJS as an example (2KB IMmutable Date time Library Alternative to moment.js with the same modern API)
Apis fall into three categories
- The first type is one that returns other objects, such as format(), which returns strings. Json () returns a JSON object
- Format () accepts two arguments, both of which have default values, and uses the default values if not passed
dayjs().format('YYYy-mm-DD' hh: MM :ss') / / the 2021-01-26 20:49:36
dayjs().format('YYYY/MM/DD hh-mm-ss SSS') / / 2021/01/26 20 to 49, 568-36
dayjs().format('YYYY year MM month DD day week WW') Tue January 26, 2021
dayjs().format('YYYY year MM month DD day week ww') // Monday, January 26, 2021
Copy the code
Dayjs ().format('YYYY') / / 2021
dayjs().format('MM') / / 01
dayjs().format('DD') / / 26
Copy the code
- Json () returns a JSON object at the current time
var date=dayjs().json()
{
"year": 2021."month": 1."date": 26."hour": 19."minute": 42."second": 41."day": 2."milliSecond": 87
}
Copy the code
- Unix timestamp (ms).valueof ()
- Unix timestamp (s).unix()
- Diff (compared: Dayjs, unit: string (default: ‘milliseconds’), float? : boolean)
- The second type returns a DayJS object and can continue to call another API after calling one API, that is, chain calls
-
Tectonic dayjs (existing? : string | number | Date | Dayjs) : construct a Dayjs instance objects
-
Cloning clone () | dayjs (the original: dayjs) : on the basis of the existing dayjs instance objects cloning returns a new dayjs instance objects
-
Verify isValid() : verifies that the dayjs instance object isValid
-
Add (value: number, unit: string)
-
Subtract (Value: Number, Unit: String)
-
StartOf (unit: string)
-
EndOf (unit: string)
// chain call
dayjs()
.startOf('month')
.add(1.'day')
.subtract(1.'year')
Copy the code
- The third class inherits from Date, which means that dayJS has the same methods that Date has. Because it is an inherited method, the method cannot return a DayJS object and cannot be called chained. (Not recommended)
3.2.4 Partial source code analysis of DAYJS
// whether d is an instance object of Dayjs
var isDayjs = d= > d instanceof Dayjs
var wrapper = (date, instance) = > dayjs(date, { locale: instance.$L })
var parseDate = function parseDate(cfg) {
var date = cfg.date,
utc = cfg.utc;
if (date === null) return new Date(NaN); // null is invalid
if (Utils.u(date)) return new Date(a);// today
if (date instanceof Date) return new Date(date);
if (typeof date === 'string'&&!/Z$/i.test(date)) {
var d = date.match(C.REGEX_PARSE);
if (d) {
var m = d[2] - 1 || 0;
var ms = (d[7] | |'0').substring(0.3);
if (utc) {
return new Date(Date.UTC(d[1], m, d[3] | |1, d[4] | |0, d[5] | |0, d[6] | |0, ms));
}
return new Date(d[1], m, d[3] | |1, d[4] | |0, d[5] | |0, d[6] | |0, ms); }}return new Date(date); // everything else
};
// The dayJS function that returns the new dayJS instance object (factory mode)
var dayjs = (date, c) = > {
// If date is an instance of Dayjs, return the cloned Dayjs instance (immutable).
if (isDayjs(date)) {
return date.clone()
}
const cfg = c || {}
cfg.date = date
return new Dayjs(cfg)
}
// Dayjs constructor
var Dayjs = /*#__PURE__*/function () {
function Dayjs(cfg) {
this.$L = parseLocale(cfg.locale, null.true);// Parse the local language
this.parse(cfg); / / core
}
var _proto = Dayjs.prototype;
_proto.parse = function parse(cfg) {
this.$d = parseDate(cfg);
this.init();
};
_proto.init = function init() {
var $d = this.$d;
this.$y = $d.getFullYear();
this.$M = $d.getMonth();
this.$D = $d.getDate();
this.$W = $d.getDay();
this.$H = $d.getHours();
this.$m = $d.getMinutes();
this.$s = $d.getSeconds();
this.$ms = $d.getMilliseconds();
}; // eslint-disable-next-line class-methods-use-this
clone() {
return wrapper(this.toDate(), this)}// Convert to a new native JavaScript Date object
toDate() {
return new Date(this.$d)
}
......
returnDayjs; } ();Copy the code
The c argument is passed in when the date argument is a Dayjs instance object and the Dayjs () function is called at the end. The c argument is an object that contains the locale attribute (locale is the language used by the last Dayjs instance object and is a string).
startOf(units, startOf) { // startOf -> endOf
constisStartOf = ! Utils.isUndefined(startOf) ? startOf :true
const unit = Utils.prettyUnit(units)
const instanceFactory = (d, m) = > {
const ins = wrapper(new Date(this.$y, m, d), this)
return isStartOf ? ins : ins.endOf(C.D)
}
const instanceFactorySet = (method, slice) = > {
const argumentStart = [0.0.0.0]
const argumentEnd = [23.59.59.999]
return wrapper(this.toDate()[method].apply( // eslint-disable-line prefer-spread
this.toDate(),
isStartOf ? argumentStart.slice(slice) : argumentEnd.slice(slice)
), this)}switch (unit) {
case C.Y:
return isStartOf ? instanceFactory(1.0) :
instanceFactory(31.11)
case C.M:
return isStartOf ? instanceFactory(1.this.$M) :
instanceFactory(0.this.$M + 1)
case C.W:
return isStartOf ? instanceFactory(this.$D - this.$W, this.$M) :
instanceFactory(this.$D + (6 - this.$W), this.$M)
case C.D:
case C.DATE:
return instanceFactorySet('setHours'.0)
case C.H:
return instanceFactorySet('setMinutes'.1)
case C.MIN:
return instanceFactorySet('setSeconds'.2)
case C.S:
return instanceFactorySet('setMilliseconds'.3)
default:
return this.clone()
}
}
Copy the code
❤️ Thank you
That is all the content of this sharing. I hope it will help you
Don’t forget to share, like and bookmark your favorite things.