像我之前的许多人一样,我试着计算两次之间的差异(工作的开始和结束时间)
我已经创建了下面的代码,但由于某些原因我得到了一个奇怪的答案。我怀疑它与创建没有日期的Date对象有关。
任何指针都会非常有教育意义,为什么我会得到一个无用的答案。
我的代码:
// Add in a rightStr() function so we can pad single number answers to two digit answers
function rightStr( myString, numChars){
return myString.slice( numChars * -1 );
}
// Input is 12:00 AM and 2:15 AM from jquery date pickers
function get_time_diff( starttime, endtime )
{
var starttime = typeof starttime !== 'undefined' ? starttime : "2014-01-01 00:00:00";
var endtime = typeof endtime !== 'undefined' ? endtime : "2014-01-01 00:00:00";
var starttime = new Date( "01/01/2000 " + starttime ).getTime();
var endtime = new Date( "01/01/2000 " + endtime ).getTime();
// Values show as 946638000000 - start
// 946646100000 - end
if( isNaN(starttime) )
{
return "";
}
if( isNaN(endtime) )
{
return "";
}
if (starttime <= endtime) {
var milisec_diff = endtime - starttime;
}else{
var milisec_diff = 0; // We don't allow negative returns
}
// milisec_diff is 8100000
// Which is 2.25 if it is divided by 60 * 60 * 1000 ( secs, mins, millisecs)
// this is a correct answer so far.
var date_diff = new Date( milisec_diff );
// date_diff = Thu Jan 01 1970 15:15:00 GMT+1300 (New Zealand Standard Time)
// this is where it goes wrong.
var hh = rightStr("0" + date_diff.getHours().toString(), 2) ;
var mm = rightStr("0" + date_diff.getMinutes().toString(), 2) ;
return hh + ":" + mm + ":00"
// returns 15:15
}
答案 0 :(得分:1)
您可以尝试这样做:第一个功能date
差异和第二个功能time
。
//Function Date difference
function dateDiffer(startdate, enddate){
var start = new Date(startdate);
var end = new Date(enddate);
var timeDiff = Math.abs(end.getTime() - start.getTime());
var Daydiff = Math.ceil(timeDiff / (1000 * 3600 * 24));
return Daydiff;
}
//Function time difference
function dateTimeDiffer(startDTime, endDtime){
var startTime = new Date(startDTime);
var endTime = new Date(endDtime);
var diff = endTime.getTime() - startTime.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;
return hh + ":" + mm + ":" + ss;
}
//call date differece
alert("Date: "+dateDiffer("7/13/2016", "12/15/2016"));
//call date time differ
alert("DateTme: "+dateTimeDiffer("08/05/2016 23:41:20", "08/06/2016 02:56:32"));
答案 1 :(得分:0)
将输入转换为Date
个对象后,您可以执行以下操作:
var time1 = "12:00 AM";
var time2 = "2:15 AM";
function timeToDate(time){
var hour = 0;
var second = 0;
if (time){
var split1 = time.split(' ');
var split2 = split1[0].split(':');
hour = parseInt(split2[0]);
second = parseInt(split2[1]);
if (split1[1] == 'PM'){
hour += 12;
}
}
return Date.UTC(2000,1,1,hour,second);
}
var date1 = timeToDate(time1);
var date2 = timeToDate(time2);
var diffInMilliseconds = date2 - date1;
console.log(diffInMilliseconds);
答案 2 :(得分:0)
您可以使用moment.js lib来处理有关datetime的所有内容
/** padding zero function */
function pad(n) {
const width = 2
const z = '0'
n = n + ''
return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n
}
/** get diff date */
function getDiffDate(d1, d2) {
/** get duration between 2 datetime */
const duration = moment.duration(d2.diff(d1))
/** get each result */
const YY = pad(duration._data.years)
const MM = pad(duration._data.months)
const DD = pad(duration._data.days)
const hh = pad(duration._data.hours)
const mm = pad(duration._data.minutes)
const ss = pad(duration._data.seconds)
/** print result ,e.g., 00-00-00 01:03:00 */
console.log(`${YY}-${MM}-${DD} ${hh}:${mm}:${ss}`)
}
/** define 2 datetime here */
const d1 = moment('2016-01-29 10:01:00')
const d2 = moment('2016-01-29 11:04:00')
getDiffDate(d1, d2)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>
答案 3 :(得分:0)
从不使用Date构造函数解析字符串(或Datep.parse,它们等同于解析)。
当你这样做时:
// Input is 12:00 AM and 2:15 AM from jquery date pickers
function get_time_diff( starttime, endtime ) {
var starttime = typeof starttime !== 'undefined' ? starttime : "2014-01-01 00:00:00";
您将 starttime 设置为字符串,以后执行:
var endtime = typeof endtime !== 'undefined' ? endtime : "2014-01-01 00:00:00";
var starttime = new Date( "01/01/2000 " + starttime ).getTime();
您正在创建一个类似&#34; 01/01/2000 12:00 AM&#34;的字符串。使用Date解析该操作完全依赖于实现,可能会导致预期结果或其他内容,包括无效日期。
始终使用自定义函数解析字符串或使用库。
正确解析字符串后,您可以通过从另一个字节中减去一个日期来获得毫秒差异。
如果您想要做的就是获得时间差异,那么根本不要创建Date对象。将时间转换为某个常用单位(可能是秒),得到差异并转换回HH:mm或其他任何内容。
将时间转换为秒的函数可以如下(应首先测试输入以确保它在可接受的范围内):
/* Convert time like 2:15:00 AM to seconds
** @param {string} s - string to pase in h:mm:ss format
** @returns {number} time converted to seconds
*/
function toSecs(s) {
var b = s.match(/\d+/g) || [];
return (b[0]%12||0)*3600 + (b[1]||0)*60 + (+b[2]||0) + (/pm$/i.test(s)? 12*3600 : 0);
}
console.log(toSecs('12:01 am'));
console.log(toSecs('12:01:01 am'));
console.log(toSecs('12:01 pm'));
&#13;