Question

I have a situation in which I am receiving date as a string in following format.

"Mon Jan 13 2014 00:00:00 GMT+0000 (GMT Standard Time)"

I need to convert it to following format in c# (Either date/string) for further processing

YYYY-MM-DD (2014-01-13)

Convert.ToDateTime(SelectedData)    

Above code thorws following error:

'Convert.ToDateTime(SelectedData)' threw an exception 
       of type 'System.FormatException' System.DateTime {System.FormatException}

Any suggestions?

I can't change the format in which I am receiving the date Best Regards.

Was it helpful?

Solution

You're going to need to use DateTime.ParseExact:

var date = DateTime.ParseExact(
    "Mon Jan 13 2014 00:00:00 GMT+0000 (GMT Standard Time)",
    "ddd MMM dd yyyy HH:mm:ss 'GMT'K '(GMT Standard Time)'",
    CultureInfo.InvariantCulture);

after parsing the date you can then send it out your way:

date.ToString("yyyy-MM-dd");

Here's an Ideone to prove it.

OTHER TIPS

Convert.ToDateTime uses standart date and time formats and this is not a standart DateTime format.

If your GMT+0000 (GMT Standard Time) is defult in your string, you can use DateTime.ParseExact instead like;

string s = "Mon Jan 13 2014 00:00:00 GMT+0000 (GMT Standard Time)";
var date = DateTime.ParseExact(s,
           "ddd MMM dd yyyy HH:mm:ss 'GMT+0000 (GMT Standard Time)'",
           CultureInfo.InvariantCulture);
Console.WriteLine(date.ToString("yyyy-MM-dd"));

Output will be;

2014-01-13

Here a demonstration.

For more information, take a loo at:

string date = SelectedData.Substring(4, 11);
string s = DateTime.ParseExact(date, "MMM dd yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top