Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
JavaScript new Date()
Method mobile terminalCompatible with ios
We often have problems with time nodes being shown as NaN on some sites, some of which are bugs and some of which are time format compatibility issues
In the actual work of development, the use of time processing is generally JavaScript framework library, but in the native development of the use of new Date() this native method for time processing, encountered the development environment time is correct, on the fruit machine but there is a time error bug, Here is the ios system time format compatibility problem. Solutions to the following problems:
Two time formats:
dateType1 = ` 2019/11/09 10:13:21 `
dateType2 = ` 2019-11-09 10:13:21 `
Copy the code
Android supports two formats. Ios supports only 2019/11/09 10:13:21
let str = 'the 2019-11-09 10:13:21' // This format is not compatible with ios using new date() ==> NaN
str = str.replace(/\-/g.'/') // Compatible with ios '2019/11/09 10:13:21'
let iosstr = '2019/11/09 10:13:21' // Compatible with ios
Copy the code
Tue May 15 2018 14:06:15 GMT+0800 (2019-11-09 10:13:21)
First is the direct new Date on Android (“2019-11-09 10:13:21”), so you can convert the time to the standard format:
In this case, android can convert both time string formats
On the ios platform, however, the time character cannot be converted.
The ios platform only recognizes the “2019-11-09 10:13:21” time string format, so we need to do a conversion to the string
let str = 'the 2019-11-09 10:13:21'
str = str.replace(/\-/g.'/') // str --> '2019/11/09 10:13:21'
new Date(str) // --> Sat Nov 09 2019 10:13:21 GMT+0800
Copy the code
This will be recognized by ios!