简体   繁体   English

使用Google脚本将日期和时间合并到DateTime中

[英]Combining Date and Time into DateTime with Google Scripts

I'm having a hard time with Date and Time objects in Javascript. 我在Javascript中使用Date和Time对象很难。

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. 从CSV文件开始,它在两个不同的单元格中包含值“12/3/2019”和“14:00:00”,并且我使用SpreadsheetApp.open()为CSV文件导入这些值。

It now seems the Date Object has the desired date, with a wrong time (11:00 instead of 14:00). 现在似乎日期对象具有所需的日期,时间错误(11:00而不是14:00)。 However, the Date Object for the time (14:00:00) get's wrong: 但是,时间(14:00:00)的日期对象出错了:

If time is set to the value "14:00" imported by the SpreadsheetApp.open() command, the following command 如果time设置为SpreadsheetApp.open()命令导入的值“14:00”,则执行以下命令

  new Date ( time )

yields something very weird: 12/31/1969 13:00:00 . 产生一些非常奇怪的东西: 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? 有没有人对如何将日期和时间对象组合成可以由CreateEvent()命令使用的东西有任何想法?

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. 如果将字符串传递给内置“Date”对象的构造函数,则参数必须采用Date.parse()方法可读的格式。 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. 其中'T'是分隔符。 More on the Date object here 更多关于Date对象的信息

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: 您可以使用Utilities.formatDate(日期,时区,格式)作为快捷方式,但这是您逐步构建模板的方法:

   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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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