Rename worksheet to cell value keeping format

2019-08-03 23:59发布

问题:

The below code works. It will rename my worksheet to a cell's value. But in the case of a new project, the cell's value happens to be a date 8/4/2012 for example. If i run the below code, the sheet gets renamed to "Sat Aug 04 2012 02:00:00 GMT-0500 (CDT)".

How can i adjust the below code so the sheet's name reflects only "8/4/2012"

  // The code below will rename the active sheet to last production week's date
var myValue = SpreadsheetApp.getActiveSheet( ).getRange("P1").getValue();
SpreadsheetApp.getActiveSpreadsheet().renameActiveSheet(myValue);

回答1:

You should use Utilities.formatDate() to get the format you want.

in your code it should be

SpreadsheetApp.getActiveSpreadsheet().renameActiveSheet(Utilities.formatDate(myValue, "GMT", "MM/dd/yyyy"));

if you're not in GMT don't forget to change that since even if you don't use hours it will mess up your dates sometimes ;-)