-
Notifications
You must be signed in to change notification settings - Fork 1
/
How to Sort a Column of Dates and Times in Google Sheets Using Apps Script
65 lines (54 loc) · 1.67 KB
/
How to Sort a Column of Dates and Times in Google Sheets Using Apps Script
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
function sortDates() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var range = sheet.getRange("A2:B6");
var values = range.getValues();
Logger.log("Original Values: " + JSON.stringify(values));
// Convert date objects to formatted date strings
values = values.map(function(row) {
return [row[0], formatDate(row[1])];
});
// Sort the formatted date strings
values.sort(function(a, b) {
return parseDateString(a[1]) - parseDateString(b[1]);
});
Logger.log("Sorted Values: " + JSON.stringify(values));
// Set the sorted values back to the range
range.setValues(values);
}
function formatDate(date) {
if (date instanceof Date) {
// Format the date as "Sun, Jun 2, 2024, 11:42 PM"
var options = {
weekday: 'short',
year: 'numeric',
month: 'short',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
hour12: true
};
return date.toLocaleString('en-US', options).replace(',', '');
}
return date;
}
function parseDateString(dateString) {
if (typeof dateString !== 'string') {
Logger.log("Invalid dateString: " + dateString);
return new Date(0);
}
var dateParts = dateString.split(' ');
if (dateParts.length < 5) {
Logger.log("Invalid format: " + dateString);
return new Date(0);
}
var dayOfWeek = dateParts[0];
var month = dateParts[1];
var day = dateParts[2];
var year = dateParts[3];
var time = dateParts[4];
var ampm = dateParts[5];
// Combine date and time parts into a valid date string
var dateStr = month + " " + day + ", " + year + " " + time + " " + ampm;
Logger.log("Parsed Date String: " + dateStr);
return new Date(dateStr);
}