将日期转换为UNIX时间戳

Conversion of Date to UNIX Timestamp

本文关键字:UNIX 时间戳 转换 日期      更新时间:2023-09-26

我在许多电子表格的Google Drive文件夹中运行了一个JavaScript函数,该函数当前正在将日期记录到日志中;

function convertDates(){
    var ui = SpreadsheetApp.getUi();
    SpreadsheetApp.getActiveSpreadsheet().toast('Conversion Started With First Row Date Cells','Conversion', 5);
    Logger.log('Date Conversion Started');
    var activeCell = SpreadsheetApp.getActiveSpreadsheet().getActiveCell();
    var cell = activeCell.getValue();
    Logger.log(cell);
 }

如何转换"细胞"的输出,目前看起来像:

 May 03, 2014 at 05:19PM

进入Javascript中的Unix时间戳?我倾向于相信这可能涉及Date()函数,但我不确定。

提前感谢。

您可以通过这种方式删除"at",然后工作表将该值识别为有效日期。

function convertDates(){
  var sheet = SpreadsheetApp.getActiveSheet();
  var range_input = sheet.getRange(1, 1);
  range_input = range_input.getValue();
  range_input = range_input.replace("at ", " ");
  sheet.getRange(1, 1).setValue(range_input);
}

我只是替换一个单元格。您可以将其循环到所有需要的单元格值。

希望能有所帮助!

如果您想获得自UNIX epoch(1970年1月1日)以来秒数的字符串表示,您可以使用这样的代码:

function convertDates(){
  var ui = SpreadsheetApp.getUi();
  SpreadsheetApp.getActiveSpreadsheet().toast('Conversion Started With First Row Date Cells','Conversion', 5);
  Logger.log('Date Conversion Started');
  var activeCell = SpreadsheetApp.getActiveSpreadsheet().getActiveCell();
  var unixEpoch = new Date(1970,0,1,0,0,0).getTime();// difference between JS epoch and UNIX epoch in milliseconds
  var cell = ((activeCell.getValue().getTime()-unixEpoch)/1000).toString();
  Logger.log(cell);
  activeCell.setValue(cell);// this will write it back to the sheet... be careful, it is not a date object anymore but a string... so the code won't work after that.
 }

您必须删除"at",并在"05:19"后添加一个空格。

看起来像这样:

var date = new Date("May 03, 2014 05:19 PM");