Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert DateTime to UK format [closed]

Tags:

c#

datetime

I want to convert the date "01/22/2013 10:00:00" to "22/01/2013 10:00:00" and my method doesn't recognise my date string.

 DateTime dt = DateTime.ParseExact(StartDate, "MM dd yyyy h:mm", CultureInfo.InvariantCulture);
            StartDate = dt.ToString("dd/M/yyyy");
 dt = DateTime.ParseExact(EndDate, "MMM dd yyyy h:mm", CultureInfo.InvariantCulture);
            EndDate = dt.ToString("dd/M/yyyy");

I am getting this error:

System.FormatException - String was not recognized as a valid DateTime.

What is the correct string format for ParseExact?

like image 681
nick gowdy Avatar asked Feb 05 '13 09:02

nick gowdy


People also ask

How do you convert DateTime to mm dd yyyy?

string date = DateTime. ParseExact(SourceDate, "dd/MM/yyyy", CultureInfo. InvariantCulture). ToString("yyyy-MM-dd");


2 Answers

Your date formatting is wrong, for the US it would be 01/22/2013 10:00:00 which is MM/dd/yyyy HH:mm:ss. For the UK it would be dd/MM/yyyy etc.

DateTime dt = DateTime.ParseExact(StartDate, "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture);

dt.ToString("dd/MM/yyyy");

Note I am assuming a 24 hour clock here which is why I use HH. If you wanted a twelve hour clock you'd need hh but then you should also put AM/PM etc.

like image 50
Lloyd Avatar answered Oct 26 '22 07:10

Lloyd


Use this code:

DateTime dt = DateTime.ParseExact(StartDate, "MM/dd/yyyy hh:mm:ss", CultureInfo.InvariantCulture);
            StartDate = dt.ToString("dd/MM/yyyy hh:mm:ss");

Notice the change to format string of ParseExact.

like image 23
Mohammad Dehghan Avatar answered Oct 26 '22 05:10

Mohammad Dehghan