Last active
April 22, 2025 02:46
-
-
Save htlin222/a9b838934af80352276a1a6c45f29b71 to your computer and use it in GitHub Desktop.
將 Google Sheets 中所有看似日期的值轉換成 YYYYMMDD 格式。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 將 Google Sheets 中所有看似日期的值轉換成 YYYYMMDD 格式。 | |
* 支援真實日期物件與常見格式字串(如 "2024-4-5", "2024/04/05", "2024.4.5")。 | |
* 用法:在 Google Sheets 的 App Script 中貼上此函式,執行 convertAnyDateToYYYYMMDD_RobustCheck()。 | |
*/ | |
function convertAnyDateToYYYYMMDD_RobustCheck() { | |
const sheet = SpreadsheetApp.getActiveSheet(); | |
const range = sheet.getDataRange(); | |
const values = range.getValues(); | |
const output = []; | |
for (let i = 0; i < values.length; i++) { | |
const row = []; | |
for (let j = 0; j < values[i].length; j++) { | |
const cell = values[i][j]; | |
// Case 1: Strong date check | |
if (isRealDate(cell)) { | |
row.push(formatDate(cell)); | |
// Case 2: String that looks like a date | |
} else if (typeof cell === 'string') { | |
const parsed = parseFlexibleDate(cell); | |
row.push(parsed ? formatDate(parsed) : cell); | |
// Other cases | |
} else { | |
row.push(cell); | |
} | |
} | |
output.push(row); | |
} | |
range.setValues(output); | |
} | |
function isRealDate(val) { | |
return Object.prototype.toString.call(val) === '[object Date]' && !isNaN(val.getTime()); | |
} | |
function formatDate(date) { | |
const y = date.getFullYear(); | |
const m = ('0' + (date.getMonth() + 1)).slice(-2); | |
const d = ('0' + date.getDate()).slice(-2); | |
return `${y}${m}${d}`; | |
} | |
function parseFlexibleDate(str) { | |
const cleaned = str.trim(); | |
const match = cleaned.match(/^(\d{4})[\s\-\/\.](\d{1,2})[\s\-\/\.](\d{1,2})$/); | |
if (match) { | |
const y = parseInt(match[1], 10); | |
const m = parseInt(match[2], 10); | |
const d = parseInt(match[3], 10); | |
if (isValidDate(y, m, d)) { | |
return new Date(y, m - 1, d); | |
} | |
} | |
return null; | |
} | |
function isValidDate(year, month, day) { | |
const date = new Date(year, month - 1, day); | |
return ( | |
date.getFullYear() === year && | |
date.getMonth() === month - 1 && | |
date.getDate() === day | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage
Paste the function in you Apps Scripts Page and run