[ACCEPTED]-C#: Making sure DateTime.Now returns a GMT + 1 time-timezone

Accepted answer
Score: 18

Use the TimeZoneInfo class found in System.Core;

You 2 must set the DateTimeKind to DateTimeKind.Utc 1 for this.

DateTime MyTime = new DateTime(1990, 12, 02, 19, 31, 30, DateTimeKind.Utc);

DateTime MyTimeInWesternEurope = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(MyTime, "W. Europe Standard Time");

Only if you're using .Net 3.5 though!

Score: 15

It depends on what you mean by "a GMT 19 + 1 timezone". Do you mean permanently 18 UTC+1, or do you mean UTC+1 or UTC+2 depending 17 on DST?

If you're using .NET 3.5, use TimeZoneInfo to 16 get an appropriate time zone, then use:

// Store this statically somewhere
TimeZoneInfo maltaTimeZone = TimeZoneInfo.FindSystemTimeZoneById("...");
DateTime utc = DateTime.UtcNow;
DateTime malta = TimeZoneInfo.ConvertTimeFromUtc(utc, maltaTimeZone );

You'll 15 need to work out the system ID for the Malta 14 time zone, but you can do that easily by 13 running this code locally:

Console.WriteLine(TimeZoneInfo.Local.Id);

Judging by your 12 comments, this bit will be irrelevant, but 11 just for others...

If you're not using .NET 10 3.5, you'll need to work out the daylight 9 savings yourself. To be honest, the easiest way 8 to do that is going to be a simple lookup 7 table. Work out the DST changes for the 6 next few years, then write a simple method 5 to return the offset at a particular UTC 4 time with that list hardcoded. You might 3 just want a sorted List<DateTime> with the known changes 2 in, and alternate between 1 and 2 hours 1 until your date is after the last change:

// Be very careful when building this list, and make sure they're UTC times!
private static readonly IEnumerable<DateTime> DstChanges = ...;

static DateTime ConvertToLocalTime(DateTime utc)
{
    int hours = 1; // Or 2, depending on the first entry in your list
    foreach (DateTime dstChange in DstChanges)
    {
        if (utc < dstChange)
        {
            return DateTime.SpecifyKind(utc.AddHours(hours), DateTimeKind.Local);
        }
        hours = 3 - hours; // Alternate between 1 and 2
    }
    throw new ArgumentOutOfRangeException("I don't have enough DST data!");
}
Score: 5

I don't think that you can set a property 9 in your code that will make DateTime.Now 8 return anything else than the current time 7 of the computer in which the code executes. If 6 you want to have a way of always getting 5 another time, you will probably need to 4 wrap in another function. You can can do 3 the round-trip over UTC and add the desired 2 offset:

private static DateTime GetMyTime()
{
    return DateTime.UtcNow.AddHours(1);
}

(code sample updated after Luke's 1 comment on the inner workings of DateTime.Now)

More Related questions