Click here to Skip to main content
15,916,280 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How can I convert this format "Fri Jan 31 2014 00:00:00 GMT-0800 (Pacific Standard Time)" to just 2014-01-31 in c#

What I have tried:

How can I convert this format "Fri Jan 31 2014 00:00:00 GMT-0800 (Pacific Standard Time)" to just 2014-01-31 in c#
Posted
Updated 16-Dec-16 1:09am

C#
string text = "Fri Jan 31 2014 00:00:00 GMT-0800 (Pacific Standard Time)";
text = text.Substring(0, text.IndexOf(" GMT"));
DateTime dt;

DateTime.TryParseExact(text, "ddd MMM d yyyy hh:mm:ss", CultureInfo.CurrentCulture, DateTimeStyles.None, out dt);

// this has the output in your desired format.  Note that DateTime variables don't
// have formats, dates only gain a format when you convert to a string so you can't
// store a date in a DateTime variable as a given format
string dateAsText = dt.ToString("yyyy-MM-dd");
 
Share this answer
 
Use one of the DateTime Structure (System)[^] conversion methods Parse, ParseExact, TryParse, or TryParseExact to convert the string to a DateTime.

Use an exact method if you know that the input is always in a defined format. The format string for your date
Fri Jan 31 2014 00:00:00 GMT-0800 (Pacific Standard Time)
is (untested) "ddd MMM dd yyyy hh:mm:ss 'GMT'zzz ".

You might strip off the time zone name from the string before parsing.

The DateTime object can then be converted back to a string using the ToString with the required output format ("yyyy-MM-dd").
 
Share this answer
 
Convert it to a DateTime:
C#
string date = "Fri Jan 31 2014 00:00:00 GMT-0800 (Pacific Standard Time)";
date = date.Substring(0, 25) + date.Substring(28, 3) + ":" + date.Substring(31, 2);
DateTime dt;
if (!DateTime.TryParseExact(date, "ddd MMM dd yyyy hh:mm:ss zzz",CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out dt))
    {
    // ... report problem
    return;
    }
dt = dt.Date;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900