【问题标题】:Set Datetime in C# based on Timezone like +08:00 [duplicate]基于时区在 C# 中设置日期时间,例如 +08:00 [重复]
【发布时间】:2021-09-20 20:42:52
【问题描述】:

我已经像这样创建了当前日期时间。

DateTime now = DateTime.UtcNow;

现在我想将其转换为不同的时区。但我在时区得到值,例如 +05:30、+07:00 等。

那么如何使用这种时区值将这个 now 值转换为特定的时区日期。

谢谢

【问题讨论】:

  • @YongShun 我试过这样,DateTimeOffset d = new DateTimeOffset(now, new TimeSpan(+5, 0, 0)); -- 但出现错误。

标签: c# asp.net .net datetime timezone


【解决方案1】:

您需要 DateTimeOffset.ToOffset(TimeSpan) 将 Utc 转换为您想要的时区。

DateTime now = DateTime.UtcNow;
DateTimeOffset dtoUtc = new DateTimeOffset(now);
TimeSpan offset = new TimeSpan(+5, 00, 00);  // Specify timezone
var dtToSpecificTimezone = dtoUtc.ToOffset(offset);

Console.WriteLine(dtToSpecificTimezone.ToString());

输出:

2021 年 7 月 11 日下午 3:02:10 +05:00

Sample program

【讨论】:

    猜你喜欢
    • 2016-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-29
    • 2021-05-31
    • 1970-01-01
    • 2018-06-03
    • 1970-01-01
    相关资源
    最近更新 更多