Home > Web Front-end > JS Tutorial > body text

How to get the current time difference using JS

亚连
Release: 2018-06-14 16:19:21
Original
2139 people have browsed it

Below I will share with you an example of JS calculating the time difference from the current time. It has a good reference value and I hope it will be helpful to everyone.

is as follows:

/**
 * JS获取距当前时间差
 * 
 * @param int time 时间戳格式
 *
 */
function get_time_diff(time) {
 var diff = '';
 var time_diff = new Date().getTime() - time; //时间差的毫秒数 
 
 //计算出相差天数 
 var days = Math.floor(time_diff / (24 * 3600 * 1000));
 if (days > 0) {
 diff += days + '天';
 }
 //计算出小时数 
 var leave1 = time_diff % ( 24 * 3600 * 1000); 
 var hours = Math.floor(leave1 / (3600 * 1000));
 if (hours > 0) {
 diff += hours + '小时';
 } else {
 if (diff !== '') {
  diff += hours + '小时';
 }
 }
 //计算相差分钟数 
 var leave2 =leave1 % (3600 * 1000);
 var minutes = Math.floor(leave2 / (60 * 1000));
 if (minutes > 0) {
 diff += minutes + '分';
 } else {
 if (diff !== '') {
  diff += minutes + '分';
 }
 }
 //计算相差秒数 
 var leave3 = leave2%(60*1000);
 var seconds = Math.round(leave3/1000);
 if (seconds > 0) {
 diff += seconds + '秒';
 } else {
 if (diff !== '') {
  diff += seconds + '秒';
 }
 }
 
 return diff;
}
Copy after login

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

How to integrate Bootstrap 4 in Laravel?

How to get the option value in the select tag in jquery

How to dynamically add option to select using js (detailed tutorial)

Connecting to MySQL in nodejs (detailed tutorial)

How to achieve seamless scrolling effect using vue.js

Use routing in vue to implement page refresh

jQuery implements recursive infinite layer function

The above is the detailed content of How to get the current time difference using JS. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template