0

I get a date with string type from API and then I parse it to a date type so that I can use it for a count down.
I want to add 30 days to the date that I've got from API.

Here is the code that I parsed

  const time = Date.parse("2020-12-30T18:35:43");

I've already read this question and I tried to implement it

Add 10 seconds to a Date

but react does not recognize the getDate

if you need more information, please let me know

louis Schneider
  • 101
  • 2
  • 9
  • If you are having frequent manipulations with date and time, a much easier solution would be to use [moment](https://momentjs.com/docs/#/manipulating/add/) – emkarachchi Jan 07 '21 at 19:32
  • Please show your attempt at implementing the duplicate, including any errors you received. – Heretic Monkey Jan 07 '21 at 19:38
  • There is no difference between a `Date` object in React and a `Date` object without React. `time`, however, is not a `Date` object. See [MDN's documentation of `Date.parse`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse), where it notes that it "returns the number of milliseconds". Note also that `new Date(string)` calls `Date.parse(string)` implicitly, so just use `new Date(string)`. – Heretic Monkey Jan 07 '21 at 19:43

2 Answers2

2

You need to wrap your parsed date with a new Date()

const time = new Date(Date.parse("2020-12-30T18:35:43"));
// As mention by other comments, this is enough
// const time = new Date("2020-12-30T18:35:43");

time.setSeconds(time.getSeconds() + 10) // 1609349753000

setSeconds and getSeconds are method of the Date, you was trying to execute them on a number.

EDIT :

Answer can be found here In a general way you should use date-fns for date manipulations ;)

jean-smaug
  • 346
  • 2
  • 11
  • it shows me an error `getSeconds is not a function` how can i fix it ? – louis Schneider Jan 07 '21 at 19:33
  • Can you give me more info about your execution context. Cause I launched it into the browser console and it's working. – jean-smaug Jan 07 '21 at 19:37
  • 3
    `new Date(string)` uses `Date.parse(string)` behind the scenes. So this would be exactly the same result.. Also the OP wants to add 30 days, not 10 seconds. – Heretic Monkey Jan 07 '21 at 19:39
  • @louisSchneider Sorry my example was based on the link you provided Here is a solution to your problem https://stackoverflow.com/questions/563406/add-days-to-javascript-date Day manipulation are tricky. I recommend you to use date-fns – jean-smaug Jan 07 '21 at 19:45
1

you can also setDate to your existing date. Check following code.

const date = new Date("2020-12-30T18:35:43");
date.setDate(date.getDate() + 30);
Zahid Hasan
  • 527
  • 4
  • 11