Reputation: 1458
I can't understand why my string value keeps throwing an exception for what should be a valid string. I have a string date in the format "30/09/2016 14:55:00"
(called myDate
) and have tried the following to get it into a datetime format:
DateTime.ParseExact(myDate, "dd/MM/yyyy HH:mm:ss", null);
DateTime.ParseExact(myDate, "dd/MM/yyyy HH:mm:ss", CultureInfo.CurrentCulture);
DateTime.Parse(myDate);
I can't see where I've gone wrong, is there something I've missed?
EDIT:
Current value of myDate
Keeps context when parse is called
The same is also true for all other versions of parsing a string to DateTime
Upvotes: 1
Views: 225
Reputation: 37299
The problem is that your string has extra "
and then when you parse it throws an exception. Your string of "30/09/2016 14:55:00"
is actually \""30/09/2016 14:55:00\""
Remove the \"
and then parse:
string myDate = "\"30/09/2016 14:55:00\"";
var result = DateTime.ParseExact(myDate.Replace("\"",""), "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
Or because it is always at the ends of the string you can use the .Trim
method
Upvotes: 1
Reputation: 176169
You string contains additional quotes which you should remove before calling DateTime.Parse
. You can remove the quotes by calling
myDate = myDate.Trim('"');
DateTime.ParseExact(myDate, "dd/MM/yyyy HH:mm:ss", null);
Upvotes: 2
Reputation: 109567
It looks like you have extra unwanted double quotes in your string.
Try this and see if it works:
var date = DateTime.ParseExact(myDate.Trim('\"'), "dd/MM/yyyy HH:mm:ss", CultureInfo.CurrentCulture);
Upvotes: 1