将UTC/GMT时间转换为本地时间

350

我们正在开发一个C#应用程序,用于Web服务客户端。该程序将在Windows XP个人电脑上运行。

Web服务返回的字段之一是DateTime字段。服务器以GMT格式返回字段,即在末尾带有“Z”。

然而,我们发现.NET似乎进行了某种隐式转换,时间总是相差12小时。

以下代码示例在某种程度上解决了这个问题,即12小时的差异已经消失,但它没有考虑到新西兰夏令时。

CultureInfo ci = new CultureInfo("en-NZ");
string date = "Web service date".ToString("R", ci);
DateTime convertedDate = DateTime.Parse(date);            

根据此日期网站

UTC/GMT 偏移量

标准时区:UTC/GMT +12小时
夏令时:+1小时
当前时区偏移量:UTC/GMT +13小时

如何调整这个额外的一小时?这可以通过程序自动完成吗?还是需要在电脑上进行某种设置?


2
“Z”时间指的是UTC时间,而非GMT时间。两者之间可能相差高达0.9秒。 - mc0e
14个回答

1

我遇到了一个问题,它在数据集被推送到客户端的过程中(从 Web 服务到客户端),由于 DataColumn 的 DateType 字段被设置为本地时间,所以它会自动更改。确保您检查 DataSets 跨越时的 DateType 是什么。

如果您不想更改它,请将其设置为 Unspecified。


0

这段代码块使用协调世界时(UTC)将当前的DateTime对象转换为本地时间。我已经测试过,效果非常好,希望能对你有所帮助!

CreatedDate.ToUniversalTime().ToLocalTime();

0
我在我的ASP.NET Core 7.0 Web API中遇到了类似的情况,我解决方法如下:
  1. 安装NodaTime Nuget。
  2. 使用CultureInfo.CurrentCulture.Name[^2..]从用户请求中获取国家代码。在我的情况下,这是IN,它将返回Asia/Kolkatta。
  3. 如果不为空,则使用ZoneId获取TimeZoneInfo,否则DateTime将导出为UTC。
  4. 现在我们可以使用TimeZoneInfo.ConvertTimeFromUtc(UTCDateTime, TimeZoneInfo)将UTC DateTime转换为用户的本地DateTime。
var timeZone = TzdbDateTimeZoneSource.Default.ZoneLocations!.FirstOrDefault(x => x.CountryCode == CultureInfo.CurrentCulture.Name[^2..]);

if (timeZone is not null) 
{
    var timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(timeZone.ZoneId);
    foreach (var order in orders)
    {
        order.OrderDate = TimeZoneInfo.ConvertTimeFromUtc(order.OrderDate.DateTime, timeZoneInfo);
    }
}

请注意,我正在使用 FirstOrDefault() 方法,这意味着对于只有一个时区的国家来说,这已经足够了。但是对于有多个时区的国家,我们需要将用户的 timezone 详细信息存储在数据库中以进行转换。

0
如果你有一个被认为不是在UTC时区的dateTime字符串,你可以使用DateTimeOffset来仅设置时区信息,而不改变字符串中的时间,如下所示:
// Input datetime string
string datetimeString = "2023-07-11 12:42:56";

// Specify the timezone as "Europe/Prague"
TimeZoneInfo pragueTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Europe/Prague");

// Parse the datetime string with the specified format
DateTime datetimeObj = DateTime.ParseExact(datetimeString, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);

// Create a DateTimeOffset with the parsed datetime and the "Europe/Prague" timezone
DateTimeOffset pragueDateTimeOffset = new DateTimeOffset(datetimeObj, pragueTimeZone.GetUtcOffset(datetimeObj));

你也可以像处理DateTime实例一样,对DateTimeOffset字符串进行格式化
// Print the resulting DateTimeOffset object
Console.WriteLine(pragueDateTimeOffset.ToString("O"));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接