Skip to content

Instantly share code, notes, and snippets.

@relyky
Last active April 3, 2024 03:27
Show Gist options
  • Save relyky/c13041774d859ab2bb888b76df4387fd to your computer and use it in GitHub Desktop.
Save relyky/c13041774d859ab2bb888b76df4387fd to your computer and use it in GitHub Desktop.
C#, DateTime.TryParseExact, parse datetime
private static DateTime? ParseDateTime(string str, string fmt)
{
DateTime dtParsed;
if (DateTime.TryParseExact(str, fmt, null, System.Globalization.DateTimeStyles.None, out dtParsed))
{
return dtParsed;
}
else
{
return null;
}
}
//---------------------
// apply
string date = "20200408";
string time = "1716";
DateTime? dtParsed = ParseDateTime($"{date}{time}", "yyyyMMddHHmm");
Console.WriteLine($"{dtParsed}");
/// <summary>
/// 解析民國年日期。只支援三種格式:九碼 YYY/MM/DD、YYY-MM-DD,或七碼 YYYMMDD。
/// </summary>
public static DateTime? ParseTwDate(string str)
{
if (String.IsNullOrWhiteSpace(str))
return null;
string twdate9 = null;
if (Regex.IsMatch(str, @"^\d{3}\d{2}\d{2}$")) // 七碼:YYYMMDD
twdate9 = str.Substring(0, 3) + "/" + str.Substring(3, 2) + "/" + str.Substring(5, 2);
else if (Regex.IsMatch(str, @"^\d{3}-\d{2}-\d{2}$")) // 九碼:YYY-MM-DD
twdate9 = str.Replace("-", "/");
else if (Regex.IsMatch(str, @"^\d{3}\/\d{2}\/\d{2}$")) // 九碼:YYY/MM/DD
twdate9 = str;
else
throw new ApplicationException($"民國年日期格式錯誤!輸入字串:{str}。");
var twCulture = new System.Globalization.CultureInfo("zh-TW") {
DateTimeFormat = {
Calendar = new TaiwanCalendar()
}
};
DateTime dt;
if (!DateTime.TryParseExact(twdate9, "yyy\\/MM\\/dd", twCulture, System.Globalization.DateTimeStyles.None, out dt))
throw new ApplicationException($"民國年日期格式錯誤!輸入字串:{str}。");
return new Nullable<DateTime>(dt);
}
/// <summary>
/// 解析民國年日期。只支援三種格式:九碼 YYY/MM/DD、YYY-MM-DD,或七碼 YYYMMDD。
/// </summary>
public static bool TryParseTwDate(string str, out DateTime? dt)
{
try
{
dt = ParseTwDate(str);
return true;
}
catch
{
dt = null;
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment