[英]Parse a string to a DateTime object
我試圖解析String
成DateTime
對象,但它似乎總是默認月份為1。所以我們可以說我給它一個字符串30/05/1970
它最終被轉換成DateTime
對象與月份值等於1
。
這是代碼:
public static DateTime ToDateTime(this String value, String format)
{
Contract.Requires(!String.IsNullOrEmpty(value));
Contract.Requires(!String.IsNullOrEmpty(format));
DateTime date;
if (DateTime.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
return date;
}
throw new ArgumentException("Input value is not a valid date.");
}
請注意,傳遞給該方法的格式為dd/mm/yyyy
。
有什么想法嗎?
您使用錯誤的格式說明符已有幾個月了。
是MM
不是mm
。 您現在將月份解析為分鍾。
使用dd/MM/yyyy
。
您可能指定了錯誤的格式。
改為這樣做
var dt= ToDateTime("30/05/1970", "dd/MM/yyyy");
並查看以下內容: http : //www.csharp-examples.net/string-format-datetime/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.