[英]C# DateTime Convert or Parse specific format?
我正在嘗試將以下字符串轉換為c#中的DateTime值:
2012年3月1日
但是在調用Convert.ToDateTime或DateTime.Parse時,我一直收到此錯誤。
無法將字符串識別為有效的DateTime。
我認為需要使用自定義日期格式,但我不知道該格式是什么。
如何將上述格式的字符串轉換為DateTime值?
DateTime.ParseExact(yourString, "d MMMM yyyy", new CultureInfo("en-US"))
您可以通過從當前線程獲取cultureinfo來找到支持的日期時間模式。
static void Main(string[] args)
{
const string date = "1 03 2012";
Console.WriteLine(Thread.CurrentThread.CurrentCulture.DateTimeFormat.LongTimePattern);
Console.WriteLine(Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortTimePattern);
Console.WriteLine(Thread.CurrentThread.CurrentCulture.DateTimeFormat.LongDatePattern);
Console.WriteLine(Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern);
Console.WriteLine(DateTime.Parse(date));
Console.WriteLine(Convert.ToDateTime(date));
Console.ReadLine();
}
這對我有用
string s = "1 March 2012";
DateTime dateTime = DateTime.Parse(s);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.