Nullbyte
Nullbyte

Reputation: 251

Having problems with a datetime string

I have this method which shall return the day of the week (Wed):

protected string GetDayOfWeek(string dateTimeString)
{
    DateTime result = DateTime.Parse(dateTimeString);
    string dayOfWeek = Enum.GetName(typeof(DayOfWeek), result.DayOfWeek);

    return dayOfWeek;    
}

I have a breakpoint on the line DateTime result to check the incoming string which gives:

"Wed, 12 Mar 2014 00:00:00 GMT"

The above method is giving me error:

"FormatException not handled by the user code" String not recognised as a valid dateTime.

What am I doing wrong? I cannot pick it up.

Upvotes: 1

Views: 88

Answers (4)

Tomas Walek
Tomas Walek

Reputation: 2544

Try using the method DateTime.ParseExact and provide an exact format string for your input. In your case the call shall look like:

DateTime myDate = DateTime.ParseExact("Wed, 12 Mar 2014 00:00:00 GMT", "ddd, dd MMM yyyy HH:mm:ss 'GMT'K", System.Globalization.CultureInfo.InvariantCulture);

Upvotes: 1

Kevin Hogg
Kevin Hogg

Reputation: 1781

There's two things going on here:

  1. Parse a string into a DateTime
  2. Get the DayOfWeek from the provided DateTime

As Tor-Erik suggests you can use DateTime.Parse with the invariant culture to get a DateTime.

DateTime.Parse(
    dateTimeString,
    System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat)

Then as Hevilávio Soares suggests you should use the built in functions of the DateTime object to obtain the Day of the week.

DateTime.Now.DayOfWeek;

It's better to separate the concerns and to reuse existing functionality than to write your own.

Upvotes: 0

h_s
h_s

Reputation: 94

You can use:

DateTime.Now.DayOfWeek;

And compare with DayOfWeekclass.

Upvotes: 1

Tor-Erik
Tor-Erik

Reputation: 1000

DateTime.Parse(string) uses the conventions of the current culture. So my guess is that "Wed, 12 Mar 2014 00:00:00 GMT" is not a valid date in your current culture.

You could try:

DateTime.Parse(dateTimeString, System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat)

That should tell the parser to be culture independent.

Upvotes: 4

Related Questions