简体   繁体   中英

Combining Date and Time into DateTime with Google Scripts

I'm having a hard time with Date and Time objects in Javascript.

Starting from a CSV file, it contains the values "12/3/2019" and "14:00:00" in two different cells and I'm importing those values with SpreadsheetApp.open() for the CSV-file.

It now seems the Date Object has the desired date, with a wrong time (11:00 instead of 14:00). However, the Date Object for the time (14:00:00) get's wrong:

If time is set to the value "14:00" imported by the SpreadsheetApp.open() command, the following command

  new Date ( time )

yields something very weird: 12/31/1969 13:00:00 .

Does anyone have any ideas about how to combines both date and time object into something which can then be used by the CreateEvent() command?

Thanks in advance for all help!

If you pass the string to the constructor of the built-in 'Date' object, the parameter must be in the format readable to the Date.parse() method. Therefore, if your plan is to parse dates from strings, construct the resulting string using the following template

2011-10-10T14:48:00

where 'T' is the delimiter. More on the Date object here

Here's the example of building the template string. You could use Utilities.formatDate(date, timezone, format) as a shortcut but this is how you build the template step by step:

   var d = new Date();

  //Date template
  var template = "YYYY-MM-DDTHH:mm:ss";

  //Year
  template = template.replace("YYYY", d.getFullYear());

  //Month. Add leading zero if required.
  template =  template.replace('MM', ("0" + (d.getMonth() + 1)).slice(-2));

  //Date. Add leading zero if required.
  template = template.replace('DD', ("0" + d.getDate()).slice(-2));

  //Hours
  template = template.replace('HH', ("0" + d.getHours()).slice(-2));

  //Minutes
  template = template.replace('mm', ("0" + d.getMinutes()).slice(-2));

  //Seconds
  template = template.replace('ss', ("0" + d.getSeconds()).slice(-2));

  Logger.log(template);

  var anotherDate = new Date(template);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM