如何格式化日期时间为GMT,不论区域设置? [英] How to format a datetime to GMT irrespective of regional settings?
问题描述
我存储在数据库中为GMT日期时间。我需要这个日期作为字符串的时区与UTC一起格式,例如:
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
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
2012-03-15T12:49:23.000+08:00
我需要的字符串输出始终表示GMT时间。
I need the string output to always represent the time in GMT.
推荐答案
这是尴尬。首先,你需要适当地分析它,然后适当地格式化......这是最容易通过的DateTimeOffset
去。 (我假设你打算输入字符串来对待,如果是在UTC?你还没有做这一点。)
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.)
您可以使用 DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal
让你最终的解析
步骤后,UTC值。然后,您可以创建一个的DateTimeOffset
从的DateTime
价值,因此会具有0偏移量。
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.
假设你有一个固定的格式输入,我的强烈的建议您使用 DateTime.ParseExact
代替的 DateTime.Parse
,太。 (实际上,我可能会建议你使用野田佳彦时间代替,但是这是一个不同的问题... )
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...)
示例代码:
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);
}
}
这篇关于如何格式化日期时间为GMT,不论区域设置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!