簡體   English   中英

使用Google腳本將日期和時間合並到DateTime中

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

我在Javascript中使用Date和Time對象很難。

從CSV文件開始,它在兩個不同的單元格中包含值“12/3/2019”和“14:00:00”,並且我使用SpreadsheetApp.open()為CSV文件導入這些值。

現在似乎日期對象具有所需的日期,時間錯誤(11:00而不是14:00)。 但是,時間(14:00:00)的日期對象出錯了:

如果time設置為SpreadsheetApp.open()命令導入的值“14:00”,則執行以下命令

  new Date ( time )

產生一些非常奇怪的東西: 12/31/1969 13:00:00

有沒有人對如何將日期和時間對象組合成可以由CreateEvent()命令使用的東西有任何想法?

在此先感謝您的幫助!

如果將字符串傳遞給內置“Date”對象的構造函數,則參數必須采用Date.parse()方法可讀的格式。 因此,如果您的計划是從字符串中解析日期,請使用以下模板構造結果字符串

2011-10-10T14:48:00

其中'T'是分隔符。 更多關於Date對象的信息

這是構建模板字符串的示例。 您可以使用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