0

Trying to add hours to a date without success.. Variables and code I have tried:

const date = '2018-10-18';
const time = '20:35';
const timezn = 2;

let end = new Date(date);
const endTimeArray = _.split(time, ':', 2);
const endHours = parseInt(endTimeArray[0]);
const endMinutes = parseInt(endTimeArray[1]);
end.setHours(end.getHours() + endHours - timezn);
end.setMinutes(end.getMinutes() + endMinutes);
const result = end.toLocaleTimeString();
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

Expected result:

"2018-10-18T20:35:00.000+02:00"
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Alex
  • 1,210
  • 3
  • 21
  • 34
  • Please update the snippet I made with the relevant library - it was not lodash as I thought - also you are missing timezn. What is wrong with `time.split(':');` – mplungjan Nov 08 '18 at 13:11
  • Nothing wrong with JS's split but since I am using lodash, I want to use it everywher – Alex Nov 08 '18 at 13:25
  • Please add timezn to the snippet – mplungjan Nov 08 '18 at 13:29
  • it's just const timezone = 2; or timezone = 3; i.o GMT+2/GMT+3 – Alex Nov 08 '18 at 13:35
  • UPDATE and then show expected and actual result. `"2018-10-18T20:35:00.000+02:00"` is certainly not a localTimeString – mplungjan Nov 08 '18 at 13:39
  • Don't you want `end.setMinutes(end.getMinutes() + endMinutes + hoursToAdd);` ??? – mplungjan Nov 08 '18 at 13:41
  • It seems you're attempting to set the local time to 20:35. Parse the date as local, then just do `date.setHours(20, 35,0,0)` (note that '2018-10-18' will be parsed as UTC). – RobG Nov 08 '18 at 22:22

1 Answers1

0

This question has already been asked, and answered, here (see user KIP)

However, for your example, the following should do.

let end = new Date(date);
let newEnd = addMinutes(end, 60);

function addMinutes(date, minutes) {
    return new Date(date.getTime() + minutes*60000);
}
cmprogram
  • 1,854
  • 2
  • 13
  • 25
  • So, I tried to set date="18.10.2018" time="20:35", however the result with your example is Start Thu Oct 18 2018 23:00:00 GMT+0300 (Eastern European Summer Time) – Alex Nov 08 '18 at 13:30
  • end = addMinutes(new Date('18.10.2018'), parseInt(hours) + parseInt(minutes/60)); – Alex Nov 08 '18 at 13:31
  • @Alex Are you saying this is what worked for you? – cmprogram Nov 08 '18 at 13:37
  • I can't see anything to recommend that approach over `date.setMinutes(date.getMinutes() + minutes)`, particularly as this answer returns a new Date rather than modifying the an existing Date (which is what the OP is doing). – RobG Nov 09 '18 at 01:03