-2

Couldn't find help in this post

I got 2 strings. For example :

let str1 = '11:00'
let str2 = '08:00'

I need to be able to get the hours difference between - in this example str1-str2=3.

I tried to parseInt() but it won't actually transform the whole string to numbers. Any ides?

falcon25
  • 11
  • 6
  • One way to do it is explained in the post you linked - pad your string with an arbitrary date and seconds and process it as a date object - then you'll be able to calculate the hours difference. – Samuel Liew Sep 20 '20 at 22:16
  • Create two dates `var date1 = new Date('11:00 01-01-2020');`, then `var date2 = new Date('8:00 01-01-2020');` and take the difference `var diff = date1.getHours() - date2.getHours();` - in case you want to plug values in do `var date1 = new Date('${str1} - 01-01-2020');` - replace ' with back tick of course. – dmitryro Sep 20 '20 at 22:21

1 Answers1

0

Use split by ":".
"regroup" [0] as hours and [1] as minutes (divide by 60).
Do the difference.
Note: Can give negative hours and long fraction.
Note: Fraction in minute format was not requested, but can be done.
Note: Fraction in fixed number of decimals was not requested, but can be done.

var str1 = "11:00";
var str2 = "08:00";

function hourMinuteStringToHourNumber(str) {
  var time = str.split(":");
  return +time[0]+time[1]/60;
};

function logDifference(timeStr1, timeStr2) {
  var time1=hourMinuteStringToHourNumber(timeStr1);
  var time2=hourMinuteStringToHourNumber(timeStr2);
  var diff=time1-time2;
  console.log(timeStr1+" - "+timeStr2+" = "+diff);
};

logDifference(str1, str2);

logDifference("18:45", "10:15");
logDifference("14:40", "10:20");
logDifference("11:23", "16:47");
.as-console-wrapper { max-height: 100% !important; top: 0; }
iAmOren
  • 2,760
  • 2
  • 11
  • 23