简体   繁体   中英

Having trouble working with dates in Google Apps Script

I'm working with a number of dates in Google Sheets, but it seems to always enter the date as a string.

sheet.getRange(3,11,sheet.getLastRow()-3, 1).setValue(Utilities.formatDate(new Date(), "UTC-5", "dd/MM/yyyy"));

is how I enter the date, but when I test it with

Logger.log(typeof extractedDate); it tells me that its a string.

If I'm working with hundreds of dates, it seems to me that it would be a huge waste of time/resources to have to parse each date as a string each time and convert it.

Instead of

sheet.getRange(3,11,sheet.getLastRow()-3, 1).setValue(Utilities.formatDate(new Date(), "UTC-5", "dd/MM/yyyy"));

use

sheet.getRange(3,11,sheet.getLastRow()-3, 1).setValue(new Date());

The above will pase the current date and time to the spreadsheet which will be displayed accordingly to the cell formatting.

If you want to pass the date without the time, instad of new Date() use

new Date(new Date().getFullYear(),new Date().getMonth() , new Date().getDate())

Better alternative

var now = new Date();
var today = now.setHours(0,0,0,0);
sheet.getRange(3,11,sheet.getLastRow()-3, 1).setValue(today);

Related

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM