Sunday, July 22, 2012

C# - Convert String to DateTime using ParseExact() method of DateTime

It is a common requirement to convert a Date/Time you have as a string to .NET native DateTime type.
The point to note here is to convey to the .NET Framework regarding the Date Format you provide as the input string. ParseExact() method of DateTime Type comes handy here.
Below is the solution to these

Convert String to DateTime in C# .NET
// String to DateTime
String dateText;
dateText = "1999-09-01 21:34 PM"; // Provide this according to your computer personal settings

DateTime myDate;
myDate = new DateTime();
myDate = DateTime.ParseExact(MyString, "yyyy-MM-dd HH:mm tt", null);

Convert DateTime to String in C# .NET
//DateTime to String
myDate = new DateTime(1999, 09, 01, 21, 34, 00);
String dateText = myDate.ToString("yyyy-MM-dd HH:mm tt");

No comments:

Post a Comment