'subtract and add time having both negative and positive time in javascript
-12:00 - 5:30 => -6:30
-2:00 - 5:30 => 3:30
00:00 - 5:30 => -5:30
6:00 - 2:30 => 3:30
i want to subtract time having both positive and negative index
let myCountries = [
{
countryName: "NewZealand",
timeDiff: "-06:30",
id: 5,
timeZone: "Pacific/Auckland"
},
{
countryName: "China",
timeDiff: "-02:30",
id: 3,
timeZone: "China Standard Time"
},
{
countryName: "GMT",
timeDiff: "+05:30",
id: 4,
timeZone: "GMT"
},
{
countryName: "India",
timeDiff: "+00:00",
id: 6,
timeZone: "Asia/Kolkata"
},
{
countryName: "Italy",
timeDiff: "+03:30",
id: 2,
timeZone: "CET"
}
]
a = "12:00";
b = "-5:30";
let beta = parseInt(a.split(":")[0]);
let gamma = parseInt(b.split(":")[1]);
Now here i want to update timeDiff with respect to the result of beta - gamma which is 6:30
So i have to now add 6 hours and 30 minutes from all the objects
After performance operation the myCountries will be as below :-
[
{
countryName: "NewZealand",
timeDiff: "00:00",
id: 5,
timeZone: "Pacific/Auckland"
},
{
countryName: "China",
timeDiff: "04:00",
id: 3,
timeZone: "China Standard Time"
},
{
countryName: "GMT",
timeDiff: "+12:00",
id: 4,
timeZone: "GMT"
},
{
countryName: "India",
timeDiff: "06:30",
id: 6,
timeZone: "Asia/Kolkata"
},
{
countryName: "Italy",
timeDiff: "+10:00",
id: 2,
timeZone: "CET"
}
a = "-12:00"; b = "=5:30";
let beta = parseInt(a.split(":")[0]);
let gamma = parseInt(b.split(":")[1]);
If the result of will be -06:30
Now i have to subtract result from timeDiff
i have already tried momentjs
Solution 1:[1]
checkout this
function diff(start, end) {
start = start.split(":");
end = end.split(":");
var startDate = new Date(0, 0, 0, start[0], start[1], 0);
var endDate = new Date(0, 0, 0, end[0], end[1], 0);
var diff = endDate.getTime() - startDate.getTime();
var hours = Math.floor(diff / 1000 / 60 / 60);
diff -= hours * 1000 * 60 * 60;
var minutes = Math.floor(diff / 1000 / 60);
return (hours < 9 ? "0" : "") + hours + ":" + (minutes < 9 ? "0" : "") + minutes;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ajeesh s |
