How to add time (both Hours & Mins) dynamically & repetitively in Javascript to auto increment date object correctly, some times I'm adding mins, or hours, or HH & mm - I want to get the new totaled time and have it return correctly incre/decremented valid time/date object.
For e.g. while adding all the hours across table rows/grids, (the duration/time being added is not known ahead of time, we dont know if its just adding mins, or hours and mins or days or increment or decremented, look at the C# call, it handles the time math correctly) some cells have mins, others have HH:mm. The answers on SO dont address incrementing, or add constant time, or add previously known fragments of the time, like adding 30 mins or don't factor dynamics times, or moving the date forward or backwards (if negative time/deductions).
So far I've been doing this manually and missing many use-cases,
var newDateObj = new Date(oldDateObj.getTime() + diff*60000);
for e.g how can I do this/dynamically, and have the newDateObj
correctly auto increment hours, or days etc.
var newDateObj = (oldDateObj) + AddMinsTimeObj; // AddTimeObj is mins here
var newDateObj = (oldDateObj) + AddHoursTimeObj; // 2Hrs hours here
var newDateObj = (oldDateObj) + AddHoursMinsTimeObj; // Add 1:40 here
var newDateObj = (oldDateObj) + AddDaysHoursMinsTimeObj; // Add days hours mins
in other langs, java, C# you can just add time, dates, time spans, System.DateTime addDynamicTimeOrDuration = today.Add(duration);
where duration can feedin 1hr:30
mins, or 220 mins
etc. How to do the same in Javascript.
Update 1: Many have suggested I use the momentjs duration
, however from the link momentjs does not have the function & this link it shows you cannot create duration from 2 datetime objects either by subtraction or create!
Update2:
I am trying this.. getting closer
moment().add($this.val + moment().diff(date1, date1))
;
I simply want to be able to add time to time & get the correct answer from a function, (regardless of whats passed in, i.e. mins, hours or days). I feel like this should have been easier/handled by a function, and let it decide whats inside each datetime
obj and then add them together. (Why is this so hard in js? and not part of the base lib.)