1

I know that a sample date object in javascript is constructed from a string containing the year, month and day. I am building a function that takes a date and number of days as arguments and adds the days to the date and returns a new date object from the same. The approach i used is this:

a) Get the milliseconds from the date object

b) Convert the days to milliseconds

c) Add the two and then derive a date object from the resultant sum. I need a way to get back to the date from the milliseconds. Thank You for your help

function AddDays(x,y){
    //convert the days to milliseconds
    let days_milli=y*24*60*60*1000;
    //get the time in millis from the date
    let days_millis=x.getTime();
    //add the times
    let total=days_milli+days_millis;
    //construct a date object from that
     //this line needs some help
    let date=getDate(total);
    return date;
}
Son of Man
  • 1,213
  • 2
  • 7
  • 27
  • 1
    Adding days as multiples of 8.64e7 milliseconds is not a good approach. It doesn't work well where daylight saving is observed as days aren't always 24 hours long. – RobG Sep 12 '21 at 08:53

1 Answers1

0

Looks like the Date class constructor has overloads to support construction of objects from a string and milliseconds. All i needed to do was to invoke new Date and then put the milliseconds in the parameter part.

function AddDays(x,y){
    //convert the days to milliseconds
    let days_milli=y*24*60*60*1000;
    //get the time in millis from the datw
    let days_millis=x.getTime();
    //add the times
    let total=days_milli+days_millis;
    //construct a date object from that
    let date=new Date(total);
    return date;
}
Son of Man
  • 1,213
  • 2
  • 7
  • 27