How to get time and convert time in JS

In Js, we usually use the new Date() method to get the current time, and the time format is like this

new Date().getTime() // 返回的的是一个long型的毫秒数
let a = new Date().getTime();	// 1675145050608
let b = new Date()	// 2023-01-31T06:04:28.113Z

When doing some time-related needs, such as counting down, calculating the remaining time, time display, etc. Need to follow:

Day-hour-minute-second form to display, so how to convert according to the obtained time?

There are already a lot of time conversion functions on the Internet for your reference. Here is another way to implement it, especially when designing the calculation of time, it will be easier to use.

For example, there is such a requirement related to time, set a deadline, get the current time, calculate the time difference between the two times, if the current time is less than or equal to the deadline, then perform operation A, if the current time > deadline, Then proceed to operation B.

In the above code snippet, we know that calling the getTime() method can convert the time into milliseconds format, then we only need to convert this time into data of the day, hour, minute, and second types.

The idea of ​​conversion is very simple, convert milliseconds into seconds ----- divide by 1000, convert seconds into minutes ----- divide by 60,

Minutes into hours ----- divided by 60, hours into days ----- divided by 24, it should be noted that the result is an integer.

// 剩余时间 天-时-分-秒
let lefttime = endtime.getTime() - nowtime.getTime(),
   d = checkTime(Math.floor(lefttime / (1000 * 60 * 60 * 24))),		// 天
   h = checkTime(Math.floor((lefttime / (1000 * 60 * 60)) % 24)),	// 时
   m = checkTime(Math.floor((lefttime / (1000 * 60)) % 60)),		// 分
   s = checkTime(Math.floor((lefttime / 1000) % 60));			// 秒

// 将时间格式数字统一转换为两位 8 --> 08
const checkTime = (i: number) => {
    if (i < 10) { return "0" + i }
    return i;
  };

After conversion, we can get the data we want, and then perform corresponding assignments.

Guess you like

Origin blog.csdn.net/weixin_48914380/article/details/128835728