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?
string date = DateTime. ParseExact(SourceDate, "dd/MM/yyyy", CultureInfo. InvariantCulture). ToString("yyyy-MM-dd");
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With