DateTime.TryParse()、DateTime.TryParseExact()
一、DateTime.TryParse()
syntax:public static bool TryParse(string? s, IFormatProvider? provider, DateTimeStyles styles, out DateTime result)
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
DateTime dateValue;
if (DateTime.TryParse("2013/07/22", new CultureInfo("zh-TW"), DateTimeStyles.None, out dateValue))
{
Console.WriteLine(dateValue.ToString());
}
else
{
Console.WriteLine("fail");
}
Console.ReadKey();
}
}
執行結果
說明:
DateTime.TryParse() 只能接受制式時間格式做 string 轉 DateTime 型別的轉換。
範例 2
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
DateTime dateValue;
if (DateTime.TryParse("01/06/2017", new CultureInfo("zh-TW"), DateTimeStyles.None, out dateValue))
{
Console.WriteLine(dateValue.ToString());
}
else
{
Console.WriteLine("fail");
}
Console.ReadKey();
}
}
執行結果
二、DateTime.TryParseExact()
syntax:public static bool TryParseExact(string? s, string? format, IFormatProvider? provider, DateTimeStyles style, out DateTime result)
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
string dateString = "+++ 2013/07/22 @ 20:00:15:4324 +++";
DateTime dateValue;
if (DateTime.TryParseExact(dateString, "+++ yyyy/MM/dd @ HH:mm:ss:ffff +++", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateValue))
{
Console.WriteLine(dateValue.ToString());
}
else
{
Console.WriteLine("fail");
}
Console.ReadKey();
}
}
執行結果
說明:
對於這種輸入源插有客製化字元時,則 format 參數就需要加入相應於輸入源客製化字元去識別該格式,
這樣才能成功地把輸入源提取 (Exact) 出 DateTime 值。
參考資料: