Wechat applet string transfer time pit

Table of contents

1. Test environment

2. Problem phenomenon

3. Summary


Let’s talk about the conclusion first. String time conversion supports yyyy/MM/dd format. Our common yyyy-MM-dd format has compatibility issues. Processing method:

new Date(dateString.replace(/-/g, "/"))

1. Test environment

WeChat version 8.0.40, iPhone XR (system version 15.2.1), iPhone 11 (system version 16.5.1)

2. Problem phenomenon

The applet needs to determine the time difference between the time returned by the business system background and the current time. The code is as follows:

//value = '2023-09-01 12:30';
let startDate = new Date(value);
console.log("startDate.getTime()",startDate.getTime());
console.log("new Date().getTime()",new Date().getTime());
let diffValue = startDate.getTime() - new Date().getTime() 
console.log("diffValue",diffValue);

The test on the WeChat development tool was normal, and the test on the XR real machine was also normal. However, it failed to work many times when tested on a colleague's Apple 11 mobile phone. Use the preview function of WeChat development tools and open the debugging window to see from the data printed on the console

At first, I thought that the date string was incomplete, which caused the failure to obtain the time, so I changed the value to 2023-09-01 12:30:00, but the printed result was still the same. When searching for js date formatting, I found an article that used regular replacement:

function strToDate(dateStr){
	var dateStr = dateStr.replace(/-/g, "/");//现将yyyy-MM-dd类型转换为yyyy/MM/dd
	var dateTime = Date.parse(dateStr);//将日期字符串转换为表示日期的秒数
	//注意:Date.parse(dateStr)默认情况下只能转换:月/日/年 格式的字符串,但是经测试年/月/日格式的字符串也能被解析
	var data = new Date(dateTime);//将日期秒数转换为日期格式
	return data;
}

This regular expression is to replace the "-" in the string. I suddenly realized, could it be a format problem? Could it be a format problem? After modifying it according to the method in the article, the code is as follows:

let startDate = new Date(value.replace(/-/g, "/"));
console.log("startDate.getTime()",startDate.getTime());
console.log("new Date().getTime()",new Date().getTime());
let diffValue = startDate.getTime() - new Date().getTime()
console.log("diffValue",diffValue);

After making the correction, I found that I could obtain the time information normally.

The console has printed out the time correctly.

3. Summary

The solution has been introduced at the beginning, but this problem is a bit strange. WeChat versions are the same. Logically speaking, the containers running the mini programs should also be the same, but the same program has different results, which is a bit confusing.

Guess you like

Origin blog.csdn.net/caicaimaomao/article/details/132621570