user1283225
user1283225

Reputation: 215

How to format a datetime to GMT irrespective of regional settings?

I have a datetime stored in the database as GMT. I need to format this datetime as a string together with the timezone offset to UTC, for example:

DateTime date = DateTime.Parse("2012-03-15 12:49:23");
string dateAsString = date.ToString("yyyy-MM-ddTHH:mm:ss.fffzzz");

2012-03-15T12:49:23.000+00:00

This code works on my machine in the UK. When I change my regional settings to a different time zone, for example Perth, I get the following output:

2012-03-15T12:49:23.000+08:00

I need the string output to always represent the time in GMT.

Upvotes: 0

Views: 7355

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500835

It's awkward. First you need to parse it appropriately, then format it appropriately... it's easiest to go via DateTimeOffset. (I'm assuming you intend the input string to be treated as if it's in UTC? You haven't made this clear.)

You can use DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal so that you end up with a UTC value after the Parse step. You can then create a DateTimeOffset from that DateTime value, so it will have an offset of 0.

Assuming you have a fixed format input, I would strongly advise that you use DateTime.ParseExact instead of DateTime.Parse, too. (Actually, I'd probably advise you to use Noda Time instead, but that's a different matter...)

Sample code:

using System;
using System.Globalization;

class Test
{
    static void Main()
    {
        var parsed = DateTime.ParseExact("2012-03-15 12:49:23",
                                         "yyyy-MM-dd HH:mm:ss",
                                         CultureInfo.InvariantCulture,
                                         DateTimeStyles.AssumeUniversal |
                                         DateTimeStyles.AdjustToUniversal);
        var dtOffset = new DateTimeOffset(parsed);
        var output = dtOffset.ToString("yyyy-MM-ddTHH:mm:ss.fffzzz",
                                       CultureInfo.InvariantCulture);
        Console.WriteLine(output);
    }                   
}

Upvotes: 5

Related Questions