Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# DateTime Conversion from yyyy-MM-ddTHH:mm:ss to dd MMM yyyy

Tags:

c#

How to convert "yyyy-MM-ddTHH:mm:ss" into "dd MMM yyyy" format? For Instance, i want to convert 2013-04-16 05:30:05 into 16 April 2013. What is the correct method to achieve this?

like image 250
Shafiq Abbas Avatar asked Nov 20 '13 07:11

Shafiq Abbas


2 Answers

First ParseExact then do ToString (I assume that you have string object, if you have DateTime object, skip first line)

var dateTime = DateTime.ParseExact(yourDateString, "yyyy-MM-ddTHH:mm:ss", CultureInfo.InvariantCulture);

var yourNewString = dateTime.ToString("dd MMM yyyy");

Note that representation of DateTime you see in debugger is dependant on your current culture.

like image 165
Kamil Budziewski Avatar answered Oct 18 '22 17:10

Kamil Budziewski


First, a DateTime has no format. But if you've already a string that represents a DateTime with the format yyyy-MM-ddTHH:mm:ss and you want to convert it to a string-date with format dd MMM yyyy you need to parse it to DateTime first.

Therefore use DateTime.ParseExact:

DateTime dt = DateTime.ParseExact("2013-04-16 05:30:05", "yyyy-MM-dd HH:mm:ss", null); 

Now you can use DateTime.ToString:

string result = dt.ToString("dd MMM yyyy");

Note that you need to pass a different CultureInfo object to ParseExact/ToString if you want to parse with another DateTimeFormat than your current (f.e. force english month names instead of german: dt.ToString("dd MMM yyyy", CultureInfo.InvariantCulture)).

like image 43
Tim Schmelter Avatar answered Oct 18 '22 16:10

Tim Schmelter