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.
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.
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.