2

I've read a bunch of the related questions but just can't figure this one out.

This is what i have:

var days = "10"; // input is in string
var now = new Date();
var nowUtc = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
var newDate = nowUtc.setDate(nowUtc.getDate() + parseInt(days));

The values just don't seem correct so i must be doing it wrong. Can anyone help?

I want the value in the end to be ISO 8601 format.

Thanks!

RPM1984
  • 72,246
  • 58
  • 225
  • 350
  • 2
    Note that `nowUtc.setDate()` changes `nowUtc` in place, and returns a *number*, not a date. – nnnnnn Oct 24 '16 at 04:32
  • How is this a duplicate of add number of days? This question specifically mentions UTC, whilst the linked answer does not. – RPM1984 Oct 24 '16 at 04:41
  • The `var nowUtc = new Date(...)` statement uses UTC values for input, but the Date constructor expects local values so applies the current host timezone offset, hence you get unexpected results. To copy a Date instance *date*, just use `new Date(date)`. – RobG Oct 24 '16 at 04:59
  • 1
    Figured it out: `var now = new Date; var newDate = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() + parseInt(days), now.getUTCHours(), now.getUTCMinutes()));` – RPM1984 Oct 24 '16 at 05:01
  • @RPM1984—see comment above for how to copy a Date, it's much simpler than using *Date.UTC*. You could also use `new Date(now.getFullYear(), now.getMonth(), …)` but only if you're being paid for your code by length. ;-) – RobG Oct 24 '16 at 05:02
  • There's already an answer for [*How to clone a Date object in JavaScript*](http://stackoverflow.com/questions/1090815/how-to-clone-a-date-object-in-javascript). ;-) – RobG Oct 24 '16 at 05:05
  • @nnnnnn i can't post an answer, because this was closed as dupe – RPM1984 Oct 24 '16 at 05:05

2 Answers2

2

setDate changes the Date object itself. you can use nowUtc.toISOString() to get ISO 8601 string.

nowUtc.setDate(nowUtc.getDate() + parseInt(days));
var iso = nowUtc.toISOString();
Mohayemin
  • 3,841
  • 4
  • 25
  • 54
-1

Just use moment.js - a library which simplifies DateTime manipulation in JavaScript.

What you are looking for is Add function and String function.

I hope it helps you!

xShivan
  • 91
  • 2
  • 9