[英]String not correct date time format
我想將字符串轉換為DateTime,但是出現以下錯誤。
無法將字符串識別為有效的DateTime。
int firstDayOfMonth = 1;
int lastDayOfMonth = 31;
int month = 3;
int year = 2006;
string sStartDate = string.Format("{0}/{1}/{2}", firstDayOfMonth, month, year);
string eEndDate = string.Format("{0}/{1}/{2}", lastDayOfMonth, month, year);
//This one works
DateTime sDate = Convert.ToDateTime(startDate, CultureInfo.CurrentCulture.DateTimeFormat);
//This one doesnt work
DateTime eDate = Convert.ToDateTime(eEndDate, CultureInfo.CurrentCulture.DateTimeFormat);
然后我嘗試了這個
DateTime date = new DateTime(year, month, lastDayOfYear);
但后來它給了我3/1/2006
但我需要它在dd/MM/yyyy
如何將字符串轉換為dd/MMyyyy
?
為什么不使用DateTime
構造函數代替DateTime.Parse
?
DateTime sDate = new DateTime(year, month, firstDayOfMonth);
我該怎么做將字符串轉換為dd / MM / yyyy
您可以conveerrt的DateTime
到string
使用正確的格式字符串和InvariantCulture
,以防止/
得到由你的文化的實際日期分隔符代替 。
string sStartDate = sDate.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
如果需要將字符串轉換為具有特定格式的日期,則可以使用DateTime.ParseExact
例如以下示例
DateTime dt = DateTime.ParseExact("9/1/2009", "M/d/yyyy",
CultureInfo.InvariantCulture);
默認情況下, Convert.ToDateTime
方法使用CurrentCulture
設置。
您的sStartDate
為1/3/2006
但eEndDate
為31/3/2006
。
如果可以成功解析此1/3/2006
,則意味着您當前的區域性將d/M/yyyy
或M/d/yyyy
(當然,還使用了當前區域性日期分隔符 )作為標准日期和時間格式,但沒有具有dd/M/yyyy
格式。
您可以找到CurrentCulture
所有標准日期和時間格式,例如;
foreach (var format in CultureInfo.CurrentCulture.
DateTimeFormat.
GetAllDateTimePatterns())
{
Console.WriteLine(format);
}
除此之外,我同意蒂姆·施梅特爾所說的一切。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.