Can someone help me convert the string 14/04/2010 10:14:49.PM to datetime in C#.net without losing the time format?
6 Answers
var date = DateTime.ParseExact(@"14/04/2010 10:14:49.PM", @"dd/MM/yyyy hh:mm:ss.tt", null);
For string representation use
date.ToString(@"dd/MM/yyyy hh:mm:ss.tt");
Also you can create extention method like this:
public enum MyDateFormats
{
FirstFormat,
SecondFormat
}
public static string GetFormattedDate(this DateTime date, MyDateFormats format)
{
string result = String.Empty;
switch(format)
{
case MyDateFormats.FirstFormat:
result = date.ToString("dd/MM/yyyy hh:mm:ss.tt");
break;
case MyDateFormats.SecondFormat:
result = date.ToString("dd/MM/yyyy");
break;
}
return result;
}
3 Comments
jdehaan
The string representation should use hh instead of HH. During parsing the difference is not that big but for output you would get 23h instead of 11h (PM)
Tim Jarvis
The extension method also needs to be static.
Andrew Orsich
ohh, yes. It just because i haven't vs near me. Updated.
DateTime.Parse(@"14/04/2010 10:14:49.PM");
that should work, not near VS at the moment so i cannot try it