How to create a specific date in Google Script

16,227

The getMonth() method returns a "zero-indexed" number. So, it returns the number 9 for the 10th month. setDate() doesn't set the date, it sets the "Day of the Month". The name of that method is misleading.

Documentation - setDate()

So, the last two parameters that you are using in setDate() are doing nothing. You are setting the day of the month to 9.

If you want to set multiple date parameters at the same time, you need to use the new Date() method:

var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);

The month parameter accept values from 0 to 11, 0 is Jan and 11 is Dec

Date Reference

Share:
16,227
Tamir Nadav
Author by

Tamir Nadav

Updated on June 04, 2022

Comments

  • Tamir Nadav
    Tamir Nadav about 2 years

    I have a spreadsheet that asks people to enter in a day of the month when we need to send out a bill. What I want to do is create a calendar event based on that. So, essentially what I need is an event that starts at the current month, day from the spreadsheet, and continues to a specified point in time.

    var monthlyDate = row[6]; // Seventh column, monthly date of payment
    var curDate = new Date();
    var curMonth = curDate.getMonth();
    var curYear = curDate.getYear();
    curDate.setDate(curMonth, monthlyDate, curYear);
    Logger.log("Day of month: %s", monthlyDate);
    Logger.log("Current Date: %s", curDate);
    Logger.log("Current Date: %s", Date());
    

    What I'm seeing is that the monthly date is coming in as a float "6.0" for example, and no matter what I enter in for monthlyDate in the setDate line, it keeps setting the date to 10/9/15 (Today is 10/15/15). I've hard-coded that value to many different numbers, but for some reason it's just not working.

    How can I create a date (in any format) that follows the scheme "Current Month / Day from Speadsheet / Current Year" ?

  • Tamir Nadav
    Tamir Nadav over 8 years
    Okay, that makes sense. How would I use the new Date() function to set the current date, with the sole exception being the actual day? As in, what do I need to put in for the year and month? Obviously, I don't want to hardcode 2015, 10.
  • Alan Wells
    Alan Wells over 8 years
    If all you want to do is change the day of the current month, you can still use setDate(), but you need to enter the right number. You are getting the date from index 6 of the row. If that date value is already in the date format, use var newDayNumber = monthlyDate.getDate(); curDate.setDate(newDayNumber);