0

Why is setDate not declared? how do i make it accept timeMachine(1,0,0) AND timeMachine(1,"January",11)

var timeMachine=function (yearsLater,monthsLater,daysLater) {
    var dateObject=new Date();
    dateObject=dateObject.getDate();
    var newDate=new Date();
    newDate.setDate(dateObject.getDate()+daysLater);
    newDate.setMonth(dateObject.getMonth()+monthsLater);
    newDate.setYear(dateObject.getYear()+yearsLater)
    console.log(newDate);
}
timeMachine()
Maertin
  • 384
  • 1
  • 8

1 Answers1

0

getDate() returns the day of the month, So in the second line of your function you are changing dateObject from a date to a number. It seems like this line should just be deleted.

Later on in the function when you try to use dateObject.getDate() it is failing because dateObject is now a number which .getDate() doesn't apply to.

The getYear() method returns the year minus 1900 (116 now), you can use the getFullYear() method in its place to get your desired functionality.

With all those changes in place the code would look like this:

var timeMachine=function (yearsLater,monthsLater,daysLater) {
    var dateObject=new Date();
    var newDate=new Date();
    newDate.setDate(dateObject.getDate()+daysLater);
    newDate.setMonth(dateObject.getMonth()+monthsLater);
    newDate.setYear(dateObject.getFullYear()+yearsLater);
    console.log(newDate);
}

timeMachine(1, 1, 1);

I don't understand how you can make your function accept month names like "January" as the monthsLater parameter... 3 months later makes sense, "January" months later doesn't seem to.

If you have an idea in mind but need to figure out how to convert month names into numbers, there are some clever solutions here (use one of these methods if typeof monthsLater === "string") Easiest way to convert month name to month number in JS ? (Jan = 01)

Community
  • 1
  • 1
IrkenInvader
  • 4,030
  • 1
  • 12
  • 23
  • i have a new question, instead of writing newDate.setDate(dateObject.getDate()+daysLater); newDate.setMonth(dateObject.getMonth()+monthsLater); newDate.setYear(dateObject.getFullYear()+yearsLater); i want to create a for loop that loops through all the arguments and add them into var newDate. this is wat i have so far var timeMachine=function (year,month,day,hour,minute) { var dateObject=new Date(); var newDate=new Date(); for (var i = 0;arguments.length<=i; i++) { newDate= }; } – Firefalcon1155 Jan 07 '16 at 01:15