'Convert a date to numeric format google app script

I want to convert a date like this dd/mm/yyyy to numeric format but I don't find any way to do this in google app script For example I have a date in my "L2" cell so I get the value like this :

date = active_sheet.getRange("L2").getValue()

How to convert date variable to numeric format (integer) ? For example today's date in numeric format is something like 44 000

Thanks in advance



Solution 1:[1]

I believe you want to convert the date object or the date string to the serial number using Google Apps Script.

From "I think it's a date object but I'm not sure", I think that 2 patterns can be considered.

Pattern 1:

In this pattern, it supposes that the value of date = active_sheet.getRange("L2").getValue() is the date object. The sample script is as follows.

var active_sheet = SpreadsheetApp.getActiveSheet();
var date = active_sheet.getRange("L2").getValue();
var serialNumber = (new Date(date.getTime() - (1000 * 60 * date.getTimezoneOffset())).getTime() / 1000 / 86400) + 25569; // Reference: https://stackoverflow.com/a/6154953
console.log(serialNumber);

Pattern 2:

In this pattern, it supposes that the value of date = active_sheet.getRange("L2").getValue() is the string value like dd/mm/yyyy. The sample script is as follows.

var active_sheet = SpreadsheetApp.getActiveSheet();
var date = active_sheet.getRange("L2").getValue(); // or getDisplayValue()
var [d, m, y] = date.split("/");
var dateObj = new Date(y, m - 1, d);
var serialNumber = (new Date(dateObj.getTime() - (1000 * 60 * dateObj.getTimezoneOffset())).getTime() / 1000 / 86400) + 25569; // Reference: https://stackoverflow.com/a/6154953
console.log(serialNumber);

Testing:

For both of the above scripts, when a sample value of 21/04/2022 is used, 44672 is returned.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jeff Schaller