-2

After callback from pay service (when user has paid the new subscription) I want to save his new subscription to his/her account in DB. Using Mongoose I want to save new subscription start and end Dates in the user account like this:

const start = Date.now();

const end = ?

const subscription = { 
    start: start,
    end: end,
}

account.subscriptions.push(subscription);

await account.save();

I can get the subscription start date using const start = Date.now(); But how can I calculate the end date of subscription if this is a 20 days package?

I should add 20 days to start date how can I do this?

Sara Ree
  • 3,417
  • 12
  • 48

2 Answers2

2

This is one of many ways to achieve what you want.

let startDate = new Date();
let endDate = new Date();

endDate.setDate(startDate.getDate() + 20);

const subscription = { 
  start: startDate,
  end: endDate,
}

account.subscriptions.push(subscription);

await account.save();
Diogenis Siganos
  • 779
  • 7
  • 17
  • So I can use `new Date();` instead of `Date.now();` as the current date...??? – Sara Ree Jul 31 '21 at 15:34
  • Yes, you can. `Date.now()` returns the number of milliseconds since midnight 01 January, 1970 UTC. So technically both work, but I find that `new Date()` is easier to handle – Diogenis Siganos Jul 31 '21 at 15:36
0

you can add any time to a date object so if you calculate the amount of milliseconds in 20 days you can add that to the date and then you have your date 20 days in the future

var oldDateObj = new Date();
var newDateObj = new Date();
newDateObj.setTime(oldDateObj.getTime() + (20 * 24 * 60 * 60 * 1000));
console.log(newDateObj);
LeeLenalee
  • 27,463
  • 6
  • 45
  • 69
  • Note that this will be the exact duration of 20 days (as in 480 hours) later, which isn't equivalent to "the same time of day 20 days later" if you cross a daylight-saving-time boundary. Usually it's better to use `date.setDate(date.getDate() + 20)` because that's what humans ordering a subscription generally expect. (But the OP didn't specify that.) – CherryDT Jul 31 '21 at 15:37