As jvdh said, a date in a spreadsheet should be automatically converted to a JavaScript date in Google Apps Script. There's something more to your situation that we've heard so far.
On a related question from 2013, AdamL did a great job explaining how dates are represented. He also hinted at a way to convert from the numeric "serial number" (or "Epoch") date value in a spreadsheet to the Unix-style values used in JavaScript.
Here is my version of that utility. To use, just pass in the value read from the spreadsheet, like this:
var csh = SpreadsheetApp.getActiveSheet();
var date = convert2jsDate( csh.getRange('A1').getValue() );
var msg = "date = " + date;
The utility can handle existing dates, "serial numbers", or string formats that are supported by JavaScript's dateString.
/**
* Convert any spreadsheet value to a date.
* Assumes that numbers are using Epoch (days since 1 Jan 1900, e.g. Excel, Sheets).
*
* @param {object} value (optional) Cell value; a date, a number or a date-string
* will be converted to a JavaScript date. If missing or
* an unknown type, will be treated as "today".
*
* @return {date} JavaScript Date object representation of input value.
*/
function convert2jsDate( value ) {
var jsDate = new Date(); // default to now
if (value) {
// If we were given a date object, use it as-is
if (typeof value === 'date') {
jsDate = value;
}
else {
if (typeof value === 'number') {
// Assume this is spreadsheet "serial number" date
var daysSince01Jan1900 = value;
var daysSince01Jan1970 = daysSince01Jan1900 - 25569 // 25569 = days TO Unix Time Reference
var msSince01Jan1970 = daysSince01Jan1970 * 24 * 60 * 60 * 1000; // Convert to numeric unix time
var timezoneOffsetInMs = jsDate.getTimezoneOffset() * 60 * 1000;
jsDate = new Date( msSince01Jan1970 + timezoneOffsetInMs );
}
else if (typeof value === 'string') {
// Hope the string is formatted as a date string
jsDate = new Date( value );
}
}
}
return jsDate;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…