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

我的未来我决定 提交于 2019-12-23 06:01:10

问题


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.


回答1:


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);
    }                   
}


来源:https://stackoverflow.com/questions/9803904/how-to-format-a-datetime-to-gmt-irrespective-of-regional-settings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!