輸入可能為 2014/11/23 (10字符)、2014/11/1 或 2014/1/12 (9字符)、2014/1/2 (8字符),統一輸出 20141123 格式。
public string GetString(string data) {
string result = string.Empty;
if (data.Length == 10) { // 2014/11/23
result = data.Replace("/", "");
}
else if (data.Length == 9) { // 2014/11/1 或 2014/1/12
string noSlash = data.Replace("/", "");
if (data.Substring(4, 3).Replace("/", "").Length == 2) { // 月份兩位 2014/11/1
result = noSlash.Substring(0, 4) + noSlash.Substring(4, 2) + "0" + noSlash.Substring(6, 1);
} else { // 日兩位 2014/1/12
result = noSlash.Substring(0, 4) + "0" + noSlash.Substring(4, 1) + noSlash.Substring(5, 2);
}
}
else if (data.Length == 8) { // 2014/1/2
string noSlash = data.Replace("/", "");
result = noSlash.Substring(0, 4) + "0" + noSlash.Substring(4, 1) + "0" + noSlash.Substring(5, 1);
}
return result;
}
public string To8Digits(string input) {
string[] formats = { "yyyy/M/d", "yyyy/MM/d", "yyyy/M/dd", "yyyy/MM/dd" };
if (DateTime.TryParseExact(input, formats, null, DateTimeStyles.None, out DateTime dt)) {
return dt.ToString("yyyyMMdd");
}
return string.Empty; // 或拋出異常
}
優勢:自動處理閏年/月份天數校驗、代碼更簡潔、可擴展支持更多格式。