-2

I have a string variable that contains the following date time string. It's format is dd/MM/yyyy HH:mm tt

string temp = "31/12/2014 12:15 AM";

I want to assign this date time to a C# datetime varialble.

Yeasin Abedin
  • 2,081
  • 4
  • 23
  • 41
  • And...? What have you tried? Did you run into any problems with the code you have? If so, please show the code. – waka Dec 09 '14 at 09:09
  • Got a Format Exception showing : "String was not recognized as a valid DateTime." – Yeasin Abedin Dec 09 '14 at 09:11
  • `DateTime.Parse`, `DateTime.TryParse`, `DateTime.ParseExact`, and `DateTime.TryParseExact` are all easy to use with lots of options depending on how strict or flexible you want to be. – Richard Dec 09 '14 at 09:13

1 Answers1

1

If dd/MM/yyyy hh:mm tt (with your CurrentCulture's DateSeparator as well) is standard date and time format of your CurrentCulture, you can use DateTime.Parse directly.

var dt = DateTime.Parse("31/12/2014 12:15 AM");

If it is not, you can use custom date and time format with DateTime.TryParseExact like;

string s = "31/12/2014 12:15 AM";
DateTime dt;
if(DateTime.TryParseExact(s, "dd/MM/yyyy hh:mm tt", CultureInfo.InvariantCulture,
                          DateTimeStyles.None, out dt))
{
    //
}

Just a note: / format specifier has a special meaning of replace current culture or supplied culture date separator. That means if you use culture that doesn't have DateSeparator as /, your parsing operation will fail even if your string and format match exactly.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364