views:

79

answers:

2

I have a .NET WebService (written in C#), that is supposed to serve people around the world.
With each request I get the user's datetime in his own time zone with the format : yyyy/MM/dd HH:mm ZZZZ.
I have to convert the string to something representing the original date and time and specifying the time zone in GMT. I have to make some logical calculations and keep it in the database.

The regular DateTime doe's not support this. it does not have a property specifying the time zone. When I try to convert my string into DateTime - it simply converts it to my local time.

I do not want to keep my time in UTC, because I have some logic that has to run per user by his own time.

Does anyone know a C# class that handles this?

+1  A: 

It's not clear whether ZZZZ means just an offset (which isn't complete time zone information) or the name of a time zone. It matters because the offset will change over time, usually due to daylight saving time.

If it's just an offset, then DateTimeOffset from .NET 2.0SP1 will cover everything you need (but you'll have to be careful due to having incomplete information).

If it's a real time zone name, TimeZoneInfo from .NET 3.5 may help you - depending on the format of the name. That uses Windows names (e.g. "GMT standard time") instead of the more common zoneinfo names (e.g. "Europe/London"). You'll need to store a DateTime or (preferrably) DateTimeOffset along with the TimeZoneInfo.

In the future, Noda Time should be able to do this for you more easily - but it's not ready for prroduction yet.

Jon Skeet
I'm sorry, but i have to ask some more.if I get "2009/01/10 17:18:44 -0800" how do I parse it to get the timezone info and the date separately? do I have to cut the string and parse it by myself or are there built in methods that handle this?
Mohoch
@Mohoch: Hans has given you parsing code, but you need to be aware that that is *not* full time zone information. It's just the correct offset at that point in time. The same time zone is likely to have a different offset at a different time of year.
Jon Skeet
Thanks Jon. I am not interested in the location's timezone offset, just in the user's current offset. But I will keep this in mind if the scope changes.Thank you very much.
Mohoch
A: 

You can parse it with DateTimeOffset. For example:

using System;

class Program {
    static void Main(string[] args) {
        var s = "2009/01/10 17:18:44 -0800";
        var dto = DateTimeOffset.ParseExact(s, "yyyy/MM/dd HH:mm:ss zzzz", null);
        var utc = dto.UtcDateTime;
        Console.WriteLine(utc);
        Console.ReadLine();
    }
}

Output: 1/11/2009 1:18:44 AM

Hans Passant