0

I'm trying to specify the timezone on a string that I am passing to DateFormat.parse. We're currently using .net framework 2.0. Current code is

DateTimeFormatInfo DATE_FORMAT = CultureInfo.CurrentCulture.DateTimeFormat;
DateTime first = DateTime.Parse("Wed, 31 Oct 2007 8:00:00 -5", DATE_FORMAT);

But then when I do first.ToString("r"), the result is

Wed, 31 Oct 2007 09:00:00 GMT

What am I doing wrong? I also tried using DateTime.SpecifyKind method to set my DateTime object's Kind to Local, but it seems like you would need to specify the kind as local before you parse the string, if the timezone is part of the string.

My local timezone is EDT, that's what I'm ultimately trying to get this date to.

Edit - our solution:

input :

DateTime first = DateTime.SpecifyKind(DateTime.Parse("OCT 31, 2007 8:00 AM", DATE_FORMAT), DateTimeKind.Local);

output :

first.ToLocalTime().ToString("our format")

Still haven't found a way to get time zone abbreviation, like 'EDT'.

user26270
  • 6,904
  • 13
  • 62
  • 94
  • For 3.5 see: http://stackoverflow.com/questions/246498/creating-a-datetime-in-a-specific-time-zone-in-c-fx-35 – annakata Apr 09 '09 at 14:22

5 Answers5

2

Use the ToLocalTime() method before calling ToString().

first.ToLocalTime().ToString();
Samuel
  • 37,778
  • 11
  • 85
  • 87
  • This was part of the answer. I did end up having to use DateFormat.SpecifyKind when I was parsing the original date string. But then we're providing the format in the ToString() when we want to output it. – user26270 Apr 09 '09 at 17:07
1

You can use the "zz" or "zzz" date formats to give you -5 or -5:00.

stevehipwell
  • 56,138
  • 6
  • 44
  • 61
1

When you call first.ToString("r"),

Here is what based on MSDN

Represents a custom date and time format string defined by the DateTimeFormatInfo..::.RFC1123Pattern property. The pattern reflects a defined standard and the property is read-only. Therefore, it is always the same, regardless of the culture used or the format provider supplied. The custom format string is "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'".

You can pass the defined format information into ToString, try to call this method

DateTime..::.ToString Method (IFormatProvider)

Instead, and pass your DateTimeFormatInfo object.

J.W.
  • 17,991
  • 7
  • 43
  • 76
0

Have a look at the DateTimeOffset struct, I think this is what you need.

Lucero
  • 59,176
  • 9
  • 122
  • 152
0

Try using ParseExact() - you can specify what goes where.

In your case, you can parse it with:

        string str = "Wed, 31 Oct 2007 8:00:00 -5";
        string fmt = "ddd, dd MMM yyyy H:mm:ss z";

        DateTime d = DateTime.ParseExact(str, fmt, null);
        Console.WriteLine(d);
Shea
  • 11,085
  • 2
  • 19
  • 21