Wechat answering mini program time calculation logic combing

I have been monitoring the data of the party building answering applet I developed these days, and I found a problem, that is, the data of the user’s answering time is somewhat inaccurate

As shown in the figure below, the number one user, with 20 questions, even if he has no brain to answer the questions, he will not complete it in 5 seconds.

Current logic

Calculate the elapsed time through a countdown. At this time, if the countdown is no longer calculated due to pressing Home to return, the elapsed time data will be less

 

Optimization logic

Record two timestamps,

1. Start time stamp

2. The end timestamp of the answer

 

The elapsed time data is calculated by these two timestamps. In this case, the elapsed time data of the user's answer can be accurately obtained

 

API about date to timestamp

var timestamp = Date.parse(new Date());
timestamp = timestamp / 1000;

 

Specific logic

If the two date objects are of Date type, you can subtract them directly, and you get the difference in milliseconds.

 

After obtaining the millisecond difference between the two dates, it can be converted into a specific date format (xxxx year xx month xx day, xx hour xx minute xx second)

Because what we get is milliseconds, all we have to convert to seconds first. 1 second = 1000 milliseconds

	var new_date = new Date(); //Create a new date object, default the current time
	var old_date = new Date("2018-12-12 00:00:00"); //Set a point in time in the past, "yyyy-MM-dd HH:mm:ss" format date
	
	var difftime = (new_date-old_date)/1000; //Calculate the time difference and convert milliseconds to seconds
	
	var days = parseInt(difftime/86400); // 天  24*60*60*1000 
   	var hours = parseInt(difftime/3600)-24*days; // hour 60*60 total hours-past hours = current hours 
   	var minutes = parseInt(difftime%3600/60); // minutes-(day*24) take 60 seconds as a whole and take the remaining seconds and seconds/60 is the minutes
   	var seconds = parseInt(difftime%60); // Take 60 seconds as a whole and take the remaining seconds
   	
   	alert("The time difference is: "+days+" days, "+hours+" hours, "+minutes+" minutes, "+seconds+"seconds");		

 

other

It is important to note that the date must be calculated by obtaining the server time through the cloud function, not the client time.

Guess you like

Origin blog.csdn.net/qq_29528701/article/details/107014863