Convert string to Datetime dd / MM / yyyy hh: mm: ss tt
How can I convert this 7/3/2015 12:40:02 PM
to DateTime with format "dd/MM/yyyy hh:mm:ss tt"
I did like this:
BreackEndTime = DateTime.ParseExact(configViewModel.EndPause, "dd/MM/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
But I always get
The string was not recognized as a valid DateTime.
Since months and days can have one digit, use
BreackEndTime = DateTime.ParseExact(configViewModel.EndPause, "d/M/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
Custom format specifier "M" (example, d
works similarly)
The custom format specifier "M" represents the month as a number from 1 through 12 (or 1 through 13 for calendars that have 13 months). The one-digit month is formatted with no leading zero.
Update
Since the hour can also have a single digit, you must use:
DateTime.ParseExact("7/3/2015 1:52:16 PM", "d/M/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);`
... so "d/M/yyyy h:mm:ss tt"
instead of "d/M/yyyy hh:mm:ss tt"
. Note that the same goes for protocols and seconds if they can also have separate digits using "d/M/yyyy h:m:s tt"
. Hope you have some point now.
If your string 7/3/2015 12:40:02 PM
is a string, you need to use one-digit format M
specifiers as specifier and d
specifier like;
BreackEndTime = DateTime.ParseExact(configViewModel.EndPause,
"M/d/yyyy hh:mm:ss tt",
CultureInfo.InvariantCulture);
FORMAT(CM.TransactionDate,'hh:mm:ss tt')
This is the code that worked well in my case:
Console.WriteLine("deal with regex datetime: ");
string input = "11/24 5:41:00 AM";
DateTime newDate;
CultureInfo enUS = new CultureInfo("en-US");
try
{
newDate = DateTime.ParseExact(input, "M/d h:mm:ss tt", CultureInfo.InvariantCulture);
Console.WriteLine("parse result: " + newDate);
}
catch (Exception err)
{
Console.WriteLine("error parsing input string. date format is wrong or string chaged " + err);
}