uni-app develops WeChat applet and solves the problem of time formatting error displaying Invalid Date on IOS iPhone

1.Problem description

will only appear onreal machine IOS. It will not appear on iOS on the mini program simulator because of the time As long as the format contains the - symbol, it will work (but there is an ios model without errors. I tested it with Apple 11 and it will appearInvalid Date).

There are several situations, such as:

1. If new Date('2023-09-07') is written like this, an error will occur and it will become Invalid Date.

2. The backend returns this time format: 2023-09-07T11:24:04.000+0800. If you use dayjs to format dayjs(2023-09-07T11:24:04.000+0800).fORMat( 'MM/ DD HH:mm') will also display the error.

2.Solution

Solutions ✔ (four types):

1. The normal time format can be replaced directlyreplace

let time = "2020-03-30 14:39"letTF = newDate(time.replace(/-/g,'/'))

2. Usemomenttime format

moment(2022-01-05T11:24:04.000+0800).format( 'MM/DD HH:mm')

3. Change to the form YYYY/MM/DD


const date = new Date('2022-02-15') // Invina Date
 
const date = new Date('2022/02/15') // OK!

4. If you want to use the format returned by the backend: 2023-09-07T11:24:04.000+0800dayjs (It has a very small package and is very practical for small programs). You need to convert and replace the symbols '-' yourself.

// 先转换格式constresolveTimeONIOs = (time) => {
  let data = '0/0/0 00:00';
  if (time && time.indexOf('-') !== -1 && time.indexOf('+') !== -1) {
    const translate = time
      .replace(/T/g, ' ')
      .replace(/\.[\d]{3}Z/, '')
      .replace(/(-)/g, '/');
    data = translate.substring(0, translate.indexOf('.'));
  }
  return data;
}
 
const  time = '2022-01-05T11:24:04.000+0800'// 这种格式时间转换const translateTime = resolveTimeOnIos (time)  // 先转换dayjs(translateTime ).format( 'MM/DD HH:mm')  // 使用dayjs格式换格式复制代码

Guess you like

Origin blog.csdn.net/weixin_45395283/article/details/132731268
Recommended