Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert date in string to DateTime with same format

Tags:

c#

I have a string that has a date stored in it.

String date = "03-05-2013 00:00:00";

I parsed it to Datetime as follows:

DateTime Start = DateTime.Parse(date);

Start.ToString() gave me "3/5/2013 12:0:00 AM"

I also used:

DateTime Start = DateTime.ParseExact(date,"dd-MM-yyyy HH:mm:ss",CultureInfo.InvariantCulture);

Then, Start.ToString() gave me "3/5/2013 12:0:00 AM", which is the exact same result as the previous one. I need to keep the original formatting. How may I do it? Thanks.

like image 926
sunil shankar Avatar asked May 13 '26 18:05

sunil shankar


2 Answers

The format you parse with does not dictate how the DateTime is formatted when you convert the date back to a string. When you call ToString on a date it pulls the format from the current culture of the thread your code is executing on (which defaults to the culture of the machine your on).

You can override this by passing the format into ToString() i.e.

Start.ToString("dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture);

See Custom Date and Time Formats.

like image 179
James Avatar answered May 16 '26 07:05

James


You need to pass the format in the ToString() call.

Start.ToString("dd-MM-yyy HH:mm:ss");
like image 32
chead23 Avatar answered May 16 '26 09:05

chead23



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!