2017-03-08 40 views
1

什麼是錯的這個片段,導致錯誤:什麼是我的代碼導致此錯誤:字符串未被識別爲有效的DateTime

 DateTime today = DateTime.Today; 
     DateTime bday = DateTime.Parse(ctxtBirthday.Text); 
     int age = today.Year - bday.Year; 
     ctxtAge.Text = age.ToString(); 

ctxtBirthday.Text例如包括:日期:1978-03-08

ctxtAge.Text是我想要的年齡結果。

.aspx負荷是錯誤:

System.FormatException

String was not recognized as a valid DateTime.

+0

可能幫助,如果你告訴我們到底是什麼錯誤是。 – PaulF

回答

7

可能有問題與你的文化。

可以使用ParseExact()代替Parse()

DateTime bday = DateTime.ParseExact(ctxtBirthday.Text, "yyyy-MM-dd", CultureInfo.InvariantCulture); 

OR

可以在Parse()方法集所需的文化:

DateTime bday = DateTime.Parse(ctxtBirthday.Text, CultureInfo.YourCulture); // use needed culture 
+0

我試過你的解決方案,但我仍然得到相同的錯誤。我使用NpgSql可能會導致問題? – Tommy

+0

@TommyMcGee,你的代碼是純C#,NpgSql不能在這裏出問題 –

+0

@TommyMcGee,你確定文本框中的文本是正確的日期字符串嗎?也許有額外的空間或別的東西? –

相關問題