2010-09-22 67 views
0

這是要健全挺無聊的,但我不能讓一個字符串轉換成承載我試試這個日期和時間ASP.NET C#字符串爲DateTime愁楚

一個DateTime:

Response.Write(year + " " + month + " " + day + " " + hour + " " + min); 
//prints 2008 9 23 11 59 0 (represents 9/23/2008 11:59 00 AM) 
DateTime dt= new DateTime(year , month , day , hour , min , 00); 

但它告訴我,它不是一個可表示的DateTime。這裏同樣的事情。

String toParse = "9/23/2008" + " " + hour + ":" + minute + " 00 " + "AM" ; 
DateTime dt= Convert.ToDateTime(toParse); 

我有這麼多麻煩。我如何正確地做到這一點?

+0

僅供參考:不是寫的'的Response.Write(年+ 「+ +月+」「+日+」「+小時+」「+分);',它'打賭這樣做:'Response.Write(string.Format(「{0} {1} {2} {3} {4} 0」,year,month,day,hour,min));' – 2010-09-22 17:06:46

+2

第一個例子應該管用。你確定你把它正確地複製了嗎? Response.Write只寫入5個值,打印註釋顯示6個。 – Brandon 2010-09-22 17:06:55

+0

可以在失敗時發佈'toParse'的值和'dt.ToString()'的值嗎? – 2010-09-22 17:27:46

回答

2

我覺得你的問題是在這裏

+ minute + " 00 " + "AM" 

應該是:

+ minute + ":00 " + "AM" 
0
Check this link for more info:- 

http://msdn.microsoft.com/en-us/library/9xk1h71t.aspx

using System; 

    using System.Globalization; 

    public class Example 
    { 
    public static void Main() 
     { 
     Console.WriteLine("{0,-18}{1,-12}{2}\n", "Date String", "Culture", "Result"); 

     string[] cultureNames = { "en-US", "ru-RU","ja-JP" }; 
     string[] dateStrings = { "01/02/09", "2009/02/03", "01/2009/03", 
           "01/02/2009", "21/02/09", "01/22/09", 
           "01/02/23" }; 
     // Iterate each culture name in the array. 
     foreach (string cultureName in cultureNames) 
     { 
     CultureInfo culture = new CultureInfo(cultureName); 

     // Parse each date using the designated culture. 
     foreach (string dateStr in dateStrings) 
     { 
      DateTime dateTimeValue; 
      try { 
       dateTimeValue = Convert.ToDateTime(dateStr, culture); 
       // Display the date and time in a fixed format. 
       Console.WriteLine("{0,-18}{1,-12}{2:yyyy-MMM-dd}", 
            dateStr, cultureName, dateTimeValue); 
      } 
      catch (FormatException e) { 
       Console.WriteLine("{0,-18}{1,-12}{2}", 
            dateStr, cultureName, e.GetType().Name); 
      } 
     } 
     Console.WriteLine(); 
     } 
    } 
} 
+0

無論何時您發佈代碼,特別是整個班級,最好包含一些額外的信息,以瞭解它的用途或發佈原因。 – Brandon 2010-09-22 17:11:32

+0

@Brandon:我以爲代碼是自我解釋..... :)對不起 – 2010-09-22 17:15:14