how to subtract two time string (HH:MM) in javascript? - Stack Overflow

I have two time strings like 03:01 and 01:19 . I want to subtract these two,I tried like below,var tim

I have two time strings like 03:01 and 01:19 . I want to subtract these two, I tried like below,

var time1= "03:01".split(':');
var time2= "01:19".split(':');
var minutes = Math.abs(Number(time1[1])-Number(time2[1]));
var hours = Math.floor(parseInt(minutes / 60));
hours = Math.abs(Number(time1[0])-Number(time2[0])-hours);
minutes = minutes % 60;
if(hours.toString().length == 1){
  hours = '0'+hours;
}
if(minutes.toString().length == 1){
  minutes = '0'+minutes;
}
console.log(hours+':'+minutes);

I have two time strings like 03:01 and 01:19 . I want to subtract these two, I tried like below,

var time1= "03:01".split(':');
var time2= "01:19".split(':');
var minutes = Math.abs(Number(time1[1])-Number(time2[1]));
var hours = Math.floor(parseInt(minutes / 60));
hours = Math.abs(Number(time1[0])-Number(time2[0])-hours);
minutes = minutes % 60;
if(hours.toString().length == 1){
  hours = '0'+hours;
}
if(minutes.toString().length == 1){
  minutes = '0'+minutes;
}
console.log(hours+':'+minutes);

Expected Answer -> 01:42

Actual Answer -> 02:18

Can someone tell me,where I am doing wrong ?

Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Jul 19, 2019 at 10:58 RanjithaBaskaranRanjithaBaskaran 531 silver badge5 bronze badges 4
  • Did you check the data type of your variables time1 and time2? – Krishna Prashatt Commented Jul 19, 2019 at 11:01
  • var hours1 = Number(time1.split(":")[0]) might help you – Rafalon Commented Jul 19, 2019 at 11:02
  • @Rafalon It's in the correct format only var time1= document.getElementById('id1').value.split(':'); var time2= document.getElementById('id2').value.split(':'); – RanjithaBaskaran Commented Jul 19, 2019 at 11:07
  • 1 Well, this is not what you wrote in your question. You might want to edit your question to include this, as it is relevant. – Rafalon Commented Jul 19, 2019 at 11:08
Add a ment  | 

1 Answer 1

Reset to default 7

Using a couple of utility functions like below might help.

Basically strToMins convert string to minutes. and minsToStr to convert back to a string.

Example below.

var time1= "03:01";
var time2= "01:19";

function strToMins(t) {
  var s = t.split(":");
  return Number(s[0]) * 60 + Number(s[1]);
}

function minsToStr(t) {
  return Math.trunc(t / 60)+':'+('00' + t % 60).slice(-2);
}

var result = minsToStr( strToMins(time1) - strToMins(time2) );
console.log(result);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745662817a4638940.html

相关推荐

  • how to subtract two time string (HH:MM) in javascript? - Stack Overflow

    I have two time strings like 03:01 and 01:19 . I want to subtract these two,I tried like below,var tim

    5小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信