首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

C# 將多種格式日期統一轉為 8 位字符串 (yyyyMMdd)

     編輯:關於.NET

需求

輸入可能為 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;
}

改進建議:使用 DateTime.ParseExact


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; // 或拋出異常
}

優勢:自動處理閏年/月份天數校驗、代碼更簡潔、可擴展支持更多格式。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved