Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert this string to date?

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?

like image 216
gog Avatar asked Feb 18 '14 13:02

gog


People also ask

Can we convert string to date in java?

We can convert String to Date in java using parse() method of DateFormat and SimpleDateFormat classes.

How do you convert strings to MM dd yyyy?

string strDate = DateTime. Now. ToString("MM/dd/yyyy");

Can we convert string to date in SQL?

In SQL Server, converting a string to date explicitly can be achieved using CONVERT(). CAST() and PARSE() functions.


1 Answers

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..

like image 132
Soner Gönül Avatar answered Oct 08 '22 20:10

Soner Gönül