I am trying to find the number of days between the current date and file creation date. The idea is to delete the files that are not more than 4 days from current date.
I used the below app script but the difference gives me a ‘NaN’ output in console
function iterateFolder() {
var folder = DriveApp.getFolderById('XXXXXXXXXXX');
console.log('Folder: ', folder.getName());
var files = folder.getFiles();
var currentDate = new Date();
var modifiedDate = Utilities.formatDate(currentDate, 'Australia/Adelaide', 'dd-MM-yyyy');
console.log('Now: ', modifiedDate);
while(files.hasNext()){
var file = files.next();
var createdDate = file.getDateCreated();
var modifiedCreatedDate = Utilities.formatDate(createdDate, 'Australia/Adelaide', 'dd-MM-yyyy');
console.log('File: ', file.getName(), ' Created On: ', modifiedCreatedDate);
console.log('Difference: ', modifiedDate - modifiedCreatedDate); // Gives NaN
}
}
2
Answers
Get the days between two dates
This modified version of your code will give you the difference(in days) between the two dates
Sample Output
References: Calculate difference between dates
Apps Script does not treat dates as strings. The
Date
object in Apps Script is built on theDate
object in JavaScript, which is…aDate
object. Doing maths with dates is possible, as shown in the following very simple snippet:In fact, that is exactly what 4thAnd1 is doing in his answer.
The problem is that in your code,
Utilities.formatDate
converts a date into a string. And arithmethic operations with strings are not possible.The recommended way to to maths with dates is using
Date.getTime
. So your code should be something like:References