How to reference today's date in JavaScript?

2019-08-14 23:40发布

问题:

I have the following code. It is an Apps Script that gets all Google Calendar events between the two dates specified.

// from https://blog.ouseful.info/2010/03/05/grabbing-google-calendar-event-details-into-a-spreadsheet/

function caltest3(){
  //http://www.google.com/google-d-s/scripts/class_calendar.html#getEvents
  // The code below will retrieve events between 2 dates for the user's default calendar and
  // display the events the current spreadsheet
  var cal = CalendarApp.getDefaultCalendar();
  var sheet = SpreadsheetApp.getActiveSheet();


  var today = new Date();
  var dd = today.getDate();
  var mm = today.getMonth()+1; //January is 0!
  var yyyy = today.getFullYear();

  var events = cal.getEvents(new Date("October 3, 2017 00:00:00"), new Date("October 3, 2017 23:00:00"));
  for (var i=0;i<events.length;i++) {
    //http://www.google.com/google-d-s/scripts/class_calendarevent.html
    var details=[[events[i].getStartTime(),  events[i].getEndTime(), events[i].getTitle(), events[i].getDescription()]];
    var row=i+1;
    var range=sheet.getRange(row,1,1,4);
    range.setValues(details);
  }
}

Currently, those two dates are hard-coded, on the line where events is declared. I have the date range set as same-date, with a focus on the first 23 hours.

However, as the script will fire daily, I cannot hard-code the two dates - they should each be dynamic, reflecting the current date.

So, in place of the hard-coded dates, how do I make use of the current date in the format "October 3, 2017" right there, whilst retaining the hard-coded times?

Yes, I have investigated and read about the Date object, but I just can't seem to cook up the right expression. A bit of extra info should help me learn it more.

回答1:

EDIT: removed +1 to month. Left it in originally from copy & paste of original code.

  var today = new Date();
  var dd = today.getDate();
  var mm = today.getMonth(); //January is 0!
  var yyyy = today.getFullYear();

  var events = cal.getEvents(new Date(yyyy, mm, dd, 0, 0, 0), new Date(yyyy, mm, dd, 23, 0, 0));


回答2:

If you look at the no-args constructor from the Date object

If no arguments are provided, the constructor creates a JavaScript Date object for the current date and time according to system settings.

you can see that making a new date object will create one for today. Notice that there is also getters/setters outlined in that document. So you can create a new Date object and set the hours/minutes/seconds to the time you want

let startDate = new Date();
startDate.setHours(0);
startDate.setMinutes(0);
startDate.setSeconds(0);

let endDate = new Date();
endDate.setHours(23);
endDate.setMinutes(0);
endDate.setSeconds(0);