Im making a post from a view and getting it in a actionresult as a string. The value I get is:
Tue Feb 18 2014 00:00:00 GMT-0300 (Hora oficial do Brasil)
Using DateTime.Parse
throws an exception:
String was not recognized as a valid DateTime.
What makes this string invalid, and how can I successfully convert it to a DateTime
?
We can convert String to Date in java using parse() method of DateFormat and SimpleDateFormat classes.
string strDate = DateTime. Now. ToString("MM/dd/yyyy");
In SQL Server, converting a string to date explicitly can be achieved using CONVERT(). CAST() and PARSE() functions.
DateTime.Parse
throws exception for this string because it does not have a standart date/time format.
If your GMT-0300 (Hora oficial do Brasil)
is stable in your string, you can use;
var s = "Tue Feb 18 2014 00:00:00 GMT-0300 (Hora oficial do Brasil)";
var date = DateTime.ParseExact(s,
"ddd MMM dd yyyy HH:mm:ss 'GMT'K '(Hora oficial do Brasil)'",
CultureInfo.InvariantCulture);
Console.WriteLine(date);
Output will be;
2/18/2014 12:00:00 AM
Here is a demonstration.
I don't think there is a way to parse your (Hora oficial do Brasil)
part except using string delimiter.
Take a look at;
The "K" Custom Format Specifier
I don't know why K
specifier doesn't work on Ideone actually. I have to put -0300
part also as a string delimiter for generating example. It can be an issue with DateTimeKind
enumeration but I'm not sure..
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