检查 Javascript 中的时间差

如何检查 Javascript 中两个文本框的时间差?

276530 次浏览

即兴发挥。减去 JavaScript Date对象以得到它们的差异:

// use a constant date (e.g. 2000-01-01) and the desired time to initialize two dates


var date1 = new Date(2000, 0, 1,  9, 0); // 9:00 AM
var date2 = new Date(2000, 0, 1, 17, 0); // 5:00 PM


// the following is to handle cases where the times are on the opposite side of
// midnight e.g. when you want to get the difference between 9:00 PM and 5:00 AM


if (date2 < date1) {
date2.setDate(date2.getDate() + 1);
}


var diff = date2 - date1;


// 28800000 milliseconds (8 hours)

然后你可以像下面这样把毫秒转换成小时、分钟和秒:

var msec = diff;
var hh = Math.floor(msec / 1000 / 60 / 60);
msec -= hh * 1000 * 60 * 60;
var mm = Math.floor(msec / 1000 / 60);
msec -= mm * 1000 * 60;
var ss = Math.floor(msec / 1000);
msec -= ss * 1000;
// diff = 28800000 => hh = 8, mm = 0, ss = 0, msec = 0

你可以像下面这样把时间转换成24小时格式的字符串:

function parseTime(s) {
var part = s.match(/(\d+):(\d+)(?: )?(am|pm)?/i);
var hh = parseInt(part[1], 10);
var mm = parseInt(part[2], 10);
var ap = part[3] ? part[3].toUpperCase() : null;
if (ap === "AM") {
if (hh == 12) {
hh = 0;
}
}
if (ap === "PM") {
if (hh != 12) {
hh += 12;
}
}
return { hh: hh, mm: mm };
}
parseTime("12:00 AM"); // {hh:  0, mm: 0}
parseTime("12:00 PM"); // {hh: 12, mm: 0}
parseTime("01:00 PM"); // {hh: 13, mm: 0}
parseTime("23:00");    // {hh: 23, mm: 0}

这是我的表演。

function get_time_difference(earlierDate, laterDate)
{
var oDiff = new Object();


//  Calculate Differences
//  -------------------------------------------------------------------  //
var nTotalDiff = laterDate.getTime() - earlierDate.getTime();


oDiff.days = Math.floor(nTotalDiff / 1000 / 60 / 60 / 24);
nTotalDiff -= oDiff.days * 1000 * 60 * 60 * 24;


oDiff.hours = Math.floor(nTotalDiff / 1000 / 60 / 60);
nTotalDiff -= oDiff.hours * 1000 * 60 * 60;


oDiff.minutes = Math.floor(nTotalDiff / 1000 / 60);
nTotalDiff -= oDiff.minutes * 1000 * 60;


oDiff.seconds = Math.floor(nTotalDiff / 1000);
//  -------------------------------------------------------------------  //


//  Format Duration
//  -------------------------------------------------------------------  //
//  Format Hours
var hourtext = '00';
if (oDiff.days > 0){ hourtext = String(oDiff.days);}
if (hourtext.length == 1){hourtext = '0' + hourtext};


//  Format Minutes
var mintext = '00';
if (oDiff.minutes > 0){ mintext = String(oDiff.minutes);}
if (mintext.length == 1) { mintext = '0' + mintext };


//  Format Seconds
var sectext = '00';
if (oDiff.seconds > 0) { sectext = String(oDiff.seconds); }
if (sectext.length == 1) { sectext = '0' + sectext };


//  Set Duration
var sDuration = hourtext + ':' + mintext + ':' + sectext;
oDiff.duration = sDuration;
//  -------------------------------------------------------------------  //


return oDiff;
}

此函数返回与 datetime 字符串和当前 datetime 不同的字符串。

function get_time_diff( datetime )
{
var datetime = typeof datetime !== 'undefined' ? datetime : "2014-01-01 01:02:03.123456";


var datetime = new Date( datetime ).getTime();
var now = new Date().getTime();


if( isNaN(datetime) )
{
return "";
}


console.log( datetime + " " + now);


if (datetime < now) {
var milisec_diff = now - datetime;
}else{
var milisec_diff = datetime - now;
}


var days = Math.floor(milisec_diff / 1000 / 60 / (60 * 24));


var date_diff = new Date( milisec_diff );


return days + " Days "+ date_diff.getHours() + " Hours " + date_diff.getMinutes() + " Minutes " + date_diff.getSeconds() + " Seconds";
}

在 GoogleChromeconsole中进行测试(按 F12)

get_time_diff()
1388534523123 1375877555722
"146 Days 12 Hours 49 Minutes 27 Seconds"

当我尝试同一时间戳之间的差异,它给0天5小时30分钟

为了得到精确的结果,我减去了5小时30分钟

function get_time_diff( datetime )
{
var datetime = typeof datetime !== 'undefined' ? datetime : "2014-01-01 01:02:03.123456";


var datetime = new Date(datetime).getTime();
var now = new Date().getTime();


if( isNaN(datetime) )
{
return "";
}


console.log( datetime + " " + now);


if (datetime < now) {
var milisec_diff = now - datetime;
}else{
var milisec_diff = datetime - now;
}


var days = Math.floor(milisec_diff / 1000 / 60 / (60 * 24));


var date_diff = new Date( milisec_diff );


return days + "d "+ (date_diff.getHours() - 5) + "h " + (date_diff.getMinutes() - 30) + "m";
}

这是对 Dmd733答案的补充。我用 Day 的持续时间修复了这个 bug (我希望我修复了,但是还没有能够测试所有的情况)。

我还快速地在结果中添加了一个 String 属性,该属性保存了通过的一般时间(对不起,使用了错误的嵌套 if!).例如,如果用于 UI 并指示什么时候更新(比如 RSS 提要)。虽然有点不合时宜,但还是很不错的:

function getTimeDiffAndPrettyText(oDatePublished) {


var oResult = {};


var oToday = new Date();


var nDiff = oToday.getTime() - oDatePublished.getTime();


// Get diff in days
oResult.days = Math.floor(nDiff / 1000 / 60 / 60 / 24);
nDiff -= oResult.days * 1000 * 60 * 60 * 24;


// Get diff in hours
oResult.hours = Math.floor(nDiff / 1000 / 60 / 60);
nDiff -= oResult.hours * 1000 * 60 * 60;


// Get diff in minutes
oResult.minutes = Math.floor(nDiff / 1000 / 60);
nDiff -= oResult.minutes * 1000 * 60;


// Get diff in seconds
oResult.seconds = Math.floor(nDiff / 1000);


// Render the diffs into friendly duration string


// Days
var sDays = '00';
if (oResult.days > 0) {
sDays = String(oResult.days);
}
if (sDays.length === 1) {
sDays = '0' + sDays;
}


// Format Hours
var sHour = '00';
if (oResult.hours > 0) {
sHour = String(oResult.hours);
}
if (sHour.length === 1) {
sHour = '0' + sHour;
}


//  Format Minutes
var sMins = '00';
if (oResult.minutes > 0) {
sMins = String(oResult.minutes);
}
if (sMins.length === 1) {
sMins = '0' + sMins;
}


//  Format Seconds
var sSecs = '00';
if (oResult.seconds > 0) {
sSecs = String(oResult.seconds);
}
if (sSecs.length === 1) {
sSecs = '0' + sSecs;
}


//  Set Duration
var sDuration = sDays + ':' + sHour + ':' + sMins + ':' + sSecs;
oResult.duration = sDuration;


// Set friendly text for printing
if(oResult.days === 0) {


if(oResult.hours === 0) {


if(oResult.minutes === 0) {
var sSecHolder = oResult.seconds > 1 ? 'Seconds' : 'Second';
oResult.friendlyNiceText = oResult.seconds + ' ' + sSecHolder + ' ago';
} else {
var sMinutesHolder = oResult.minutes > 1 ? 'Minutes' : 'Minute';
oResult.friendlyNiceText = oResult.minutes + ' ' + sMinutesHolder + ' ago';
}


} else {
var sHourHolder = oResult.hours > 1 ? 'Hours' : 'Hour';
oResult.friendlyNiceText = oResult.hours + ' ' + sHourHolder + ' ago';
}
} else {
var sDayHolder = oResult.days > 1 ? 'Days' : 'Day';
oResult.friendlyNiceText = oResult.days + ' ' + sDayHolder + ' ago';
}


return oResult;
}

以下是对我有效的解决方案:

var date1 = new Date("08/05/2015 23:41:20");
var date2 = new Date("08/06/2015 02:56:32");


var diff = date2.getTime() - date1.getTime();


var msec = diff;
var hh = Math.floor(msec / 1000 / 60 / 60);
msec -= hh * 1000 * 60 * 60;
var mm = Math.floor(msec / 1000 / 60);
msec -= mm * 1000 * 60;
var ss = Math.floor(msec / 1000);
msec -= ss * 1000;


console.log(hh + ":" + mm + ":" + ss);

我喜欢通过 Epoch 来做。

var now = new Date();
var future = new Date(now.setMinutes(15));


var futureEpoch = moment(future).unix();
var nowEpoch = moment(now).unix();
var differenceInEpoch = nowEpoch - scheduledEpoch ;


console.log("futureEpoch        : " + futureEpoch);
console.log("nowEpoch              : " + nowEpoch);
console.log("differenceInEpoch     : " + differenceInEpoch);


var diffTime = new Date(0); // The 0 there is the key, which sets the date to the epoch
diffTime.setUTCSeconds(differenceInEpoch);
console.log("new diffTime : " + diffTime);

时间差以毫秒为单位

firstDate.getTime() - secondDate.getTime()

在我的例子中,我将把时间以毫秒为单位存储在 chrome 存储器中,并试图在几个小时后找到差异。

function timeDiffInHours(milliseconds){
time_diff = (new Date).getTime() - milliseconds
return parseInt((time_diff/(1000*60*60)) % 24)
}


// This is again sending current time and diff would be 0.
timeDiffInHours((new Date).getTime());

我对计时器计数器做了一些改进

//example return : 01:23:02:02
//               : 1 Day 01:23:02:02
//               : 2 Days 01:23:02:02




function get_timeDifference(strtdatetime) {
var datetime = new Date(strtdatetime).getTime();
var now = new Date().getTime();


if (isNaN(datetime)) {
return "";
}


//console.log(datetime + " " + now);


if (datetime < now) {
var milisec_diff = now - datetime;
} else {
var milisec_diff = datetime - now;
}


var days = Math.floor(milisec_diff / 1000 / 60 / (60 * 24));


var date_diff = new Date(milisec_diff);










var msec = milisec_diff;
var hh = Math.floor(msec / 1000 / 60 / 60);
msec -= hh * 1000 * 60 * 60;
var mm = Math.floor(msec / 1000 / 60);
msec -= mm * 1000 * 60;
var ss = Math.floor(msec / 1000);
msec -= ss * 1000




var daylabel = "";
if (days > 0) {
var grammar = " ";
if (days > 1) grammar = "s "
var hrreset = days * 24;
hh = hh - hrreset;
daylabel = days + " Day" + grammar ;
}




//  Format Hours
var hourtext = '00';
hourtext = String(hh);
if (hourtext.length == 1) { hourtext = '0' + hourtext };


//  Format Minutes
var mintext = '00';
mintext = String(mm);
if (mintext.length == 1) { mintext = '0' + mintext };


//  Format Seconds
var sectext = '00';
sectext = String(ss);
if (sectext.length == 1) { sectext = '0' + sectext };


var msectext = '00';
msectext = String(msec);
msectext = msectext.substring(0, 1);
if (msectext.length == 1) { msectext = '0' + msectext };


return daylabel + hourtext + ":" + mintext + ":" + sectext + ":" + msectext;
}

我只使用 getTime();和例如 Date.now()来返回毫秒的差值:

 //specified date:


var oneDate = new Date("November 02, 2017 06:00:00");


//number of milliseconds since midnight Jan 1 1970 till specified date


var oneDateMiliseconds = oneDate.getTime();


////number of milliseconds since midnight Jan 1 1970 till now


var currentMiliseconds = Date.now();


//return time difference in miliseconds


alert(currentMiliseconds-oneDateMiliseconds);

试试这个:

function SumHours() {
var smon = document.getElementById('sMon').value ;
var fmon = document.getElementById('fMon').value ;
var diff = 0 ;
if (smon && fmon) {
smon = ConvertToSeconds(smon);
fmon = ConvertToSeconds(fmon);
diff = Math.abs( fmon - smon ) ;
console.log( 'time difference is : ' + secondsTohhmmss(diff) );
}


function ConvertToSeconds(time) {
var splitTime = time.split(":");
return splitTime[0] * 3600 + splitTime[1] * 60;
}


function secondsTohhmmss(secs) {
var hours = parseInt(secs / 3600);
var seconds = parseInt(secs % 3600);
var minutes = parseInt(seconds / 60) ;
return hours + "hours : " + minutes + "minutes ";
}
}
<td>
<input type="time" class="dataInput" id="sMon" onchange="SumHours();" />
</td>


<td>
<input type="time" class="dataInputt" id="fMon" onchange="SumHours();"/>
</td>

你可以使用 moment js 来实现这个目的。 moment js‘ from Now ()’会给你与当前时间的任何时间差。

var m1 = any date time on moment format;


console.log(m1.fromNow());

使用这个函数可以得到两次不同的结果。

 /**
* Get Two Time Different
* @param join
* @param lastSeen
* @param now
* @returns {string}
*/
function getTimeDiff( join, lastSeen, now = false)
{
let t1 = new Date(join).getTime(), t2 = new Date(lastSeen).getTime(), milliseconds =0, time ='';
if (now) t2 = Date.now();
if( isNaN(t1) || isNaN(t2) ) return '';
if (t1 < t2) milliseconds = t2 - t1; else milliseconds = t1 - t2;
var days = Math.floor(milliseconds / 1000 / 60 / (60 * 24));
var date_diff = new Date( milliseconds );
if (days > 0) time += days + 'd ';
if (date_diff.getHours() > 0) time += date_diff.getHours() + 'h ';
if (date_diff.getMinutes() > 0) time += date_diff.getMinutes() + 'm ';
if (date_diff.getSeconds() > 0) time += date_diff.getSeconds() + 's ';
return time;
}
    

    

console.log(getTimeDiff(1578852606608, 1579530945513));

var moment = require("moment");
var momentDurationFormatSetup = require("moment-duration-format")


var now  = "2015-07-16T16:33:39.113Z";
var then = "2015-06-16T22:33:39.113Z";


var ms = moment(now,"YYYY-MM-DD'T'HH:mm:ss:SSSZ").diff(moment(then,"YYYY-MM-DD'T'HH:mm:ss:SSSZ"));
var d = moment.duration(ms);
var s = d.format("dd:hh:mm:ss");
console.log(s);

可以通过在 end 和 updatedAt 中插入值来设置自定义差异

getDifference(theDate: string): string {
let end = moment(moment(moment()).valueOf());
let updatedAt = moment(new Date(theDate).valueOf());
let diff = end.diff(updatedAt, "hour", false);
if (diff > 8760) {
diff = end.diff(updatedAt, "years", false);
return diff > 1 ? diff + " years ago" : diff + " year ago";
} else if (diff > 730) {
diff = end.diff(updatedAt, "months", false);
return diff > 1 ? diff + " months ago" : diff + " month ago";
} else if (diff > 24) {
diff = end.diff(updatedAt, "days", false);
return diff > 1 ? diff + " days ago" : diff + " day ago";
} else if (diff <= 0) {
diff = end.diff(updatedAt, "minutes", false);
return diff > 1 ? diff + " minutes ago" : diff + " minute ago";
} else return diff > 1 ? diff + " hours ago" : diff + " hour ago";

}

获得“6小时23分27秒”或“3年5个月3天14小时3分3秒”等输出。

let MILISECONDS = 1000
let YEAR_IN_SECONDS = 31536000
let MONTHS_IN_SECONDS = 2592000
let DAY_IN_SECONDS = 86400
let HOUR_IN_SECONDS = 3600
let MINUTES_IN_SECONDS = 60


let TIME_LENGTHS = [
{seconds: YEAR_IN_SECONDS, term: 'years'},
{seconds: MONTHS_IN_SECONDS, term: 'months'},
{seconds: DAY_IN_SECONDS, term: 'days'},
{seconds: HOUR_IN_SECONDS, term: 'hours'},
{seconds: MINUTES_IN_SECONDS, term: 'minutes'},
{seconds: 1, term: 'seconds'}
]
const timeInUnitsFormat = function (start) {
let messageJoins = []
let now = new Date()
let diffInSeconds = parseInt((now.getTime() - start.getTime()) / MILISECONDS)
for (let tl of TIME_LENGTHS) {
if (diffInSeconds >= tl.seconds) {
let num_of_times = diffInSeconds / tl.seconds
diffInSeconds = diffInSeconds % tl.seconds
messageJoins.push(`${num_of_times} ${tl.term}`)
}
}
return messageJoins.join(',')
}

Ehsan 的回答开始,但是它有意地捕获了绝对值。下午4点和上午1点(9小时)之间的差异计算为15小时。

function hoursDiff() {
let sTime = document.getElementById('sTime').value,
eTime = document.getElementById('eTime').value;


if (sTime && eTime) {
let diff = toSeconds(eTime) - toSeconds(sTime);
if (diff < 0) diff = 86400 + diff; // adding because diff is negative
console.log('time difference is : ' + fromSeconds(diff));
}


function toSeconds(time) {
let splitTime = time.split(":");
return splitTime[0] * 3600 + splitTime[1] * 60;
}


function fromSeconds(secs) {
let hours = parseInt(secs / 3600),
seconds = parseInt(secs % 3600),
minutes = parseInt(seconds / 60);
return hours + "hours : " + minutes + "minutes ";
}
}
<td>
<input type="time" class="dataInput" id="sTime" onchange="hoursDiff();" />
</td>


<td>
<input type="time" class="dataInputt" id="eTime" onchange="hoursDiff();"/>
</td>

这就是我要怎么利用它。

我实际上并不需要 fromSeconds,这只是为了说明这里。

我将返回 diff来调度服务器启动后 cron 作业间隔的第一个实例。看起来像这样

setTimeout(() => {
myCronFunc();
setInterval(myCronFunc, 86400 * 1000);
},hoursDiff(new Date().toLocaleTimeString("en-us", {timeStyle: "medium"}), "1:00:00 AM"));

function hoursDiff(sTime, eTime) {


if (sTime && eTime) {
let diff = toSeconds(eTime) - toSeconds(sTime);
if (diff < 0) diff = 86400 + diff; // adding because diff is negative
console.log(diff);
console.log('time difference is : ' + fromSeconds(diff));
return diff * 1000;
}


function toSeconds(time) {
let splitTime = time.split(/[: ]/);
if (splitTime[3].toUpperCase() == 'PM') splitTime[0] = +splitTime[0] + 12;
return (splitTime[0] * 3600) + (splitTime[1] * 60) + +splitTime[2];
}


function fromSeconds(secs) {
let hours = parseInt(secs / 3600),
seconds = parseInt(secs % 3600),
minutes = parseInt(seconds / 60);
return hours + "hours : " + minutes + "minutes ";
}
}


hoursDiff(new Date().toLocaleTimeString("en-us", {timeStyle: "medium"}),"9:00:00 AM");