4

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

Transformer
  • 6,963
  • 2
  • 26
  • 52
  • 2
    Dates and times in js is quite unpleasant to work with, i would look into something like [`moment.js`](https://momentjs.com/) if i were you. – Olian04 Dec 28 '17 at 21:35
  • 1
    @Olian04 yes I am finding that out, doing it on my own is giving me a lot of headaches. So, I want something to simply add two time correctly in JS, _my challenge with momentjs is you have to specify ahead of time, which I wont know always, if the user entered days or hours_, for e.g. `moment('November 1977').fromNow()` // '34 years ago' its a lot of rewrite to parse out, and error prone. `moment().add('days', 2).calendar(); // 'Monday at 8:30 AM'` - here it requires I know I am adding days ahead of time!! – Transformer Dec 28 '17 at 21:41
  • I'm not sure I understand you. What do you mean by `here it requires I know I am adding days ahead of time`? – Olian04 Dec 28 '17 at 21:45
  • but how can you possibly do the calculation if you don't know what you're adding? – Giacomo Cosimato Dec 28 '17 at 21:45
  • @GiacomoCosimato I am adding dateTime variables from a input box, `the fragements of which part of the time is not know` for e.g, I dont know if I am adding just mins or hours & mins ahead of time. The user could have typed just secs, or hours or mins. – Transformer Dec 28 '17 at 21:47
  • the previous SO samples, js code is very specific to adding mins, or hours, I want it to be able to handle all three and not worry about it. – Transformer Dec 28 '17 at 21:48
  • 1
    ok, but at some point you do know what you've got, right? So you should be able to use a library or whatever other method. – Giacomo Cosimato Dec 28 '17 at 21:49
  • 2
    You can `moment().add(Duration)` where `Duration` is a special moment object that can be seconds, minutes, days, whatever. https://momentjs.com/docs/#/durations/ – Chris Riebschlager Dec 28 '17 at 21:49
  • I strongly recommend moment.js here. –  Dec 28 '17 at 21:50
  • 1
    anyway, a simple solution would be to convert everything to milliseconds and then do the sum. – Giacomo Cosimato Dec 28 '17 at 21:51
  • 1
    @ChrisRiebschlager that what I was looking for awesome. I dont see how to extract duration form two dateobjects from that help page, _can you please tell me if a user enters some time, using that `userEnterTimeObject` and `myDateObj` how can I pass a couple date objects to it and get the duration_, so that I may add it to back to another date? – Transformer Dec 28 '17 at 21:55
  • 1
    @GiacomoCosimato thats actually a good idea and I have been limping by with it, how however I am not able to handle some cases like increments/decrements to next day. I guess that should be two separate functions, I was hoping there was func/lib out there. – Transformer Dec 28 '17 at 21:57
  • what do you mean? If you convert everything to milliseconds, you can work with unix timestamps. You get the initial timestamp with `getTime`, then if you want to add a day, you sum the duration of a day in ms. `new Date().getTime() + 8.64e+7;` – Giacomo Cosimato Dec 28 '17 at 22:04
  • 1
    If I understand you correctly, you can create a duration based on the milliseconds produced by moment's `diff` function on those two dates. https://momentjs.com/docs/#/displaying/difference/ But at that point, you don't really need a duration. You could just `moment.add()` those milliseconds. – Chris Riebschlager Dec 28 '17 at 22:07
  • 1
    @ChrisRiebschlager I was looking at `duration create, subtraction & add` functions. I am not sure why diff and subtraction are posted as different items, I see `diff` _as a subset of `subtractive` functions_. I'm testing this and the other options now, if you can post the date diff date sample I can mark as answer thanks. – Transformer Dec 28 '17 at 22:13
  • @GiacomoCosimato after reading your comment, I looked up unix timestamps. Looks like if I have to specifically mention the unix time format in windows and then it might work. let me try to test this if it will work for me, – Transformer Dec 28 '17 at 22:16
  • I think you can use [`moment().add(Duration)`](https://momentjs.com/docs/#/manipulating/add/) as already suggested. Can you provide sample values of `AddMinsTimeObj`, `AddHoursTimeObj` etc? Providing a MVCE is the best way to get a good working solution. – VincenzoC Dec 28 '17 at 22:59
  • @VincenzoC the sample code is listed above, 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 handled by a function, and let it decide whats inside each `datetime` obj and then add them together. – Transformer Dec 30 '17 at 10:43
  • @transformer I asked for sample *values* of `AddMinsTimeObj`, `AddHoursTimeObj` etc. How does your _datetime obj_ look like? Moment can parse ISO 8601 duration (e.g. `P1Y2M3DT4H5M6S`) and strings like `7 23:59:59.999`. – VincenzoC Dec 30 '17 at 11:35
  • @VincenzoC ok I understand now :) strings from datetime objects `08:22` sometimes `08` *.* `22` or just `0822` or `22`. for all practical purposes my input assumes they are entering hours worked... this is the reason why I am trying to find an easy way to manage those diff inputs and add the time through a lib/function. In my case, the user never enters dates, just the hours and mins in the input box ( a numeric text box, that does not exceed 24 HH:MM) in .5 steps/increments – Transformer Dec 31 '17 at 21:38

1 Answers1

1

Using Moment.js, you can find the difference in milliseconds between any two date objects.

let birthday = moment([1978,7,12]);
let ageInMs = moment().diff(birthday);

That will give you a number of milliseconds between those two Moment objects. You don't need to know how many seconds, minutes, hours or day are contained within to do some Moment math.

let doubleMyAge = moment().add(ageInMs, 'ms');

The result will be a Moment object that is my current age into the future, i.e. a very long time from now.

Chris Riebschlager
  • 1,323
  • 1
  • 8
  • 12
  • Chris from your link I was trying to chain this with two arguments in a function, I was trying something like this in a function, `moment().add($this.val + moment().diff(date1, date1))` – Transformer Dec 28 '17 at 22:39
  • `diff` doesn't quite work that way. You call it on a moment object instead of sending it two parameters. so it'd be more like `date1.diff(date2)` if `date1` and `date2` are both moment objects. – Chris Riebschlager Dec 28 '17 at 22:47
  • 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 handled by a function, and let it workout whats inside each `datetime obj` and then add them together. – Transformer Dec 30 '17 at 10:45