問題提出:在一個新聞資訊添加網頁的製作過程中,有一項要求記錄新聞發布時間的欄位。按要求,我先設計一個textbox控制項,寫入值: this.timebox.Text = System.DateTime.Now.ToString("yyyy-mm-dd hh:mm:ss");
在VS內建的程式開發伺服器瀏覽時頁面都是正常的,當發布後使用IIS時就出現了上圖的錯誤,有點摸不著頭腦,錯誤原因應該可以鎖定為IIS導致的時間格式問題。
tempEntity.CreateTime = DateTime.ParseExact(mdr["CREATETIME"].ToString(), "yyyy-M-d H:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.AllowInnerWhite);
改為預設的即可:
tempEntity.CreateTime = Convert.ToDateTime(mdr["CREATETIME"].ToString());
這樣當頁面載入時,出現正常時間顯示。
儲存網頁添加資訊時:寫入資料庫值,應該把字元型資料重新轉換為日期型:
DateTime fbtime = Convert.ToDateTime(this.timebox.Text.Trim());
結題報錯為:該字串未被識別為有效DateTime
解決辦法:
代碼如下 |
複製代碼 |
輸入值時改為: this.timebox.Text = System.DateTime.Now.ToString("s"); 取值是: DateTime fbtime = DateTime.Parse(Convert.ToDateTime(this.timebox.Text.Trim()).ToString("yyyy-MM-dd")); |
DateTime.Parse 方法 (String)
將日期和時間的指定字串表示轉換成其等效的 DateTime。
代碼如下 |
複製代碼 |
using System; using System.Globalization; namespace Parse { class Class1 { public static void Main(string[] args) { // Assume the current culture is en-US. // The date is Feburary 16, 1992, 12 hours, 15 minutes and 12 seconds. string myDateTimeValue = "2/16/1992 12:15:12"; DateTime myDateTime = DateTime.Parse(myDateTimeValue); Console.WriteLine("1) myDateTime = {0}", myDateTime); // Reverse month and day to conform to a different culture. // The date is Feburary 16, 1992, 12 hours, 15 minutes and 12 seconds. IFormatProvider culture = new CultureInfo("fr-FR", true); string myDateTimeFrenchValue = " 16/02/1992 12:15:12"; DateTime myDateTimeFrench = DateTime.Parse(myDateTimeFrenchValue, culture, DateTimeStyles.NoCurrentDateDefault); Console.WriteLine("2) myDateTimeFrench = {0}", myDateTimeFrench); // The date is Feburary 16, 1992, 12 hours, 15 minutes and 12 seconds. string[] expectedFormats = {"G", "g", "f" ,"F"}; myDateTimeFrench = DateTime.ParseExact(myDateTimeFrenchValue, expectedFormats, culture, DateTimeStyles.AllowWhiteSpaces); Console.WriteLine("3) myDateTimeFrench = {0}", myDateTimeFrench); } } } /* This example yields the following results: 1) myDateTime = 2/16/1992 12:15:12 PM 2) myDateTimeFrench = 2/16/1992 12:15:12 PM 3) myDateTimeFrench = 2/16/1992 12:15:12 PM */ |
DateTime.ParseExact Method (String, String, IFormatProvider)