How to get a date format string from a sheet cell?

前端 未结 2 760
轮回少年
轮回少年 2020-12-19 22:51

In a google script function I need to get a date value from a google sheets I have done something like this

var csh = SpreadsheetApp.getActiveSheet();
var da         


        
相关标签:
2条回答
  • 2020-12-19 23:22

    apps script automatically converts Spreadsheet dates to Javascript dates. when I run your code, msg is equal to "date = Wed Nov 11 2015 00:00:00 GMT+0100 (CET)" for me.

    If this doesn't work for you for some reasons you might want to try to use new Date(); e.g. date = new Date(date);

    0 讨论(0)
  • 2020-12-19 23:40

    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;
    }
    
    0 讨论(0)
提交回复
热议问题