How to set the format of a spreadsheet cell to "date" using SpreadSheetApp and google App script

I need to set the format of a cell to "date" in a google spreadsheet with google app script (preferably with the spreadsheet app), so that when a persons clicks the cell a calendar pops up.

Upvotes: 0

Views: 203

Answers (2)

Rend
Rend

Reputation: 56

If you want the calendar to show when you click a cell, do it like this:

var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var range = sheet.getRange("A1:A10"); 
range.setNumberFormat("dd/MM/yyyy"); 
range.setDataValidation(SpreadsheetApp.newDataValidation().requireDate().setAllowInvalid(false).build());

Upvotes: 0

ross
ross

Reputation: 2774

This can be achieved with the .setNumberFormat() method.


Example

See function below (adapted from Google's documentation):

function setFormat() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0];

  var cell = sheet.getRange("B2");
  // Set to date format
  cell.setNumberFormat("yyyy-mm-dd");
}

Note: If you're trying to achieve this for a larger range (more than 1 cell), you'll need to use .setNumberFormats() instead, here's the documentation for that method.


References

Upvotes: 3

Related Questions