Use Datetime.UTC to set West Central Africa time

Viewed 217

I need to save the Datetime of where my client Software works.

The client is based in West Central Africa. I used Datetime.Now during development and was working fine but in production, the time displayed is -1 hour late. How do I make use of Datetime.Utc to show the exact time.

Note that West Central Africa is utc+1.

I have tried the below but it only shows UTC+1

TimeZoneInfo NaijaZone = TimeZoneInfo.FindSystemTimeZoneById("W. Central Africa Standard Time");
2 Answers

If you only want to show W Africa time (regardless of client), then you can do something like this:

var utc = DateTime.UtcNow;

//this is your stated offset from UTC
//Caveat: Daylight Savings, if/when applicable
var offset = 1;

Console.WriteLine(utc - new TimeSpan(offset *-1, 0, 0));

There will undoubtedly comments about using FindSystemTimeZoneById or similar to get W. Central Africa Standard Time (just as you have above) instead of setting the offset specifically, and if it works, then that would be the recommended way:

// Note: DateTime.UtcNow
TimeZoneInfo.ConvertTimeBySystemTimeZoneId(DateTime.UtcNow, "W. Central Africa Standard Time");

However, depending on what you mean by "production" (systems you deploy to, not in your control, what version of .Net, core, container, etc.) you may/may not have them, have different ids, etc.:

    //Note: UTC
    var utc = DateTime.UtcNow;
    try
    {
        Console.WriteLine(TimeZoneInfo.ConvertTimeBySystemTimeZoneId(utc, "W. Central Africa Standard Time"));
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
        var offset = 1;
        Console.WriteLine(utc - new TimeSpan(offset * -1, 0, 0));
        //List what's available on "this" system...
        var sysZones = TimeZoneInfo.GetSystemTimeZones();
        if (sysZones.Count > 0)
        {
            foreach (TimeZoneInfo timeZoneInfo in sysZones)
            {
                Console.WriteLine($"{timeZoneInfo.BaseUtcOffset} : {timeZoneInfo.Id}");
            }
        }
        else
        {
            Console.WriteLine("No zones here...");
        }
    }

Hth...

Related