Ian Vink
Ian Vink

Reputation: 68810

C# Parsing a long date

I have the following text that I am trying to parse into a date, but I can't seem to get the time zone correct.

Ideas?

Fri May 29 2015 00:00:00 GMT-0700 (Pacific Daylight Time)

(I can't change the date structure)

Upvotes: 0

Views: 167

Answers (2)

Ahsan Ahmad
Ahsan Ahmad

Reputation: 999

there is a shortcut way that I sometimes use.

first split the string based on space like:

 var dateString = 'Fri May 29 2015 00:00:00 GMT-0700 (Pacific Daylight Time)';
 var dateArray = stdateString.Split(' ');

second we need time. for that

var timeString = dateArray[4];
var timeArray = timeString.Split(':');

third for timezone

var timezoneString = dateArray[5];
var timezoneSignPart = timezoneString.Substring(3,1)
var timezoneHourPart = timezoneString.Substring(4,2)
var timezoneMinPart = timezoneString.Substring(6,2)

After that you may use to construct the date however you want to like

This is very personal way for me when I don't have much time to investigate what is the problem ob the coming date strings.

Upvotes: 0

shree.pat18
shree.pat18

Reputation: 21757

Try this:

 string str = "Fri May 29 2015 00:00:00 GMT-0700 (Pacific Daylight Time)";
 DateTime dt = new DateTime();
 bool b = DateTime.TryParseExact(str.Substring(0,33), "ddd MMMM dd yyyy hh:mm:ss 'GMT'zzz", null, DateTimeStyles.None, out dt);

This makes the assumption that the description of the time zone is irrelevant since the offset from GMT is given. Therefore, parsing the substring of the original date string only upto the timezone offset part should be sufficient.

Demo

Upvotes: 2

Related Questions