最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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);

发布评论

评论列表(0)

  1. 暂无评论