gpt4 book ai didi

c# - 如何以 UTC 格式打印日期时间?

转载 作者:行者123 更新时间:2023-11-30 23:04:55 26 4
gpt4 key购买 nike

我只是想以 UTC 等效时间格式打印 DateTime。我做错了什么?

var utcEpoch = DateTime.Parse("1970-01-01", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal); //This specifies the time I provided is in UTC
Console.WriteLine(utcEpoch.ToString("yyyy-MM-dd HH:mm:ss zzz")); //This properly shows my UTC offset of -6, so it's not wrong
Console.WriteLine(utcEpoch.ToString("u")); //This just flat out seems wrong because it doesn't specify a timezone or offset in its output

> 1969-12-31 18:00:00 -06:00
> 1969-12-31 18:00:00Z

我希望看到最后一个 1970-01-01 00:00:00Z

最佳答案

来自 The Universal Sortable ("u") Format Specifier :

Although the result string should express a time as Coordinated Universal Time (UTC), no conversion of the original DateTime value is performed during the formatting operation. Therefore, you must convert a DateTime value to UTC by calling the DateTime.ToUniversalTime method before formatting it. In contrast, DateTimeOffset values perform this conversion automatically; there is no need to call the DateTimeOffset.ToUniversalTime method before the formatting operation.

您的utcEpoch.Kind 不是 UTC,它是LocalDateTime's are triciker than you might think .您期望它将 UTC 作为 Kind 属性返回,但它不是。它返回 Local

这种情况已在 Phil Haack blog post 上讨论过还有Matt Johnson对此有很好的评论;

AssumeLocal and AssumeUniversal are both related to how the input string is interpreted. By themselves, neither will change the output kind.

The default output kind is Local. To get it to be Utc, you can use the AdjustToUniversal style.

The DateTimeStyles enum is flags-based, so you can combine these in some ways that make sense. To achieve what you originally set out to do (parse the input as UTC and output it as UTC), then you would use:

DateTime utcDate = DateTime.Parse("10/01/2006 19:30", culture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);

As others pointed pointed out, a separate call to ToUniversalTime() would also work, but this is technically more correct.

你可以在referance source上看到它同样;

case 'u':   // Universal time in sortable format.
if (offset != NullOffset)
{
// Convert to UTC invariants mean this will be in range
dateTime = dateTime - offset;
}
else if (dateTime.Kind == DateTimeKind.Local)
{
InvalidFormatForLocal(format, dateTime);
}

关于c# - 如何以 UTC 格式打印日期时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49087359/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com