views:

59

answers:

2

This is going to sound very silly but I can't get a string to convert into a DateTime that carries the date and time

I try this :

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);

But it tells me it is not a representable DateTime. Same thing here.

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

I'm having so much trouble. How do I do this correctly?

+2  A: 

I think your problem is here

 + minute + " 00 " + "AM" 

Should be:

 + minute + ":00 " + "AM" 
Kevin
A: 
 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();
      }
   }
}
Adi_aks
Whenever you post code, especially an entire class, it might be a good idea to include a little extra information as to what it's for or why you're posting it.
Brandon
@Brandon: I thought the code is self explainatory ..... :) Sorry
Adi_aks