gpt4 book ai didi

C# ConvertTimeFromUtc 时髦

转载 作者:行者123 更新时间:2023-11-30 14:48:23 27 4
gpt4 key购买 nike

使用下面的代码,我试图将此 datetime 字符串转换为本地 DateTime

private DateTime ConvertToLocalTime(string datetimestring)
{
DateTime timeUtc = DateTime.Parse(datetimestring);
TimeZoneInfo cstZone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
DateTime cstTime = TimeZoneInfo.ConvertTimeFromUtc(timeUtc, cstZone);
return cstTime;
}

这是我得到的异常:

at System.TimeZoneInfo.ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone, TimeZoneInfoOptions flags, CachedData cachedData) at System.TimeZoneInfo.ConvertTimeFromUtc(DateTime dateTime, TimeZoneInfo destinationTimeZone)

The conversion could not be completed because the supplied DateTime did not have the Kind property set correctly. For example, when the Kind property is DateTimeKind.Local, the source time zone must be TimeZoneInfo.Local.

ConvertTimeFromUtc 的示例看起来与我的代码完全一样,只是我将此字符串解析为 timeUtc:2017-01-23T05:00:00+00:00

如果我这样调用 Parse:

DateTime.Parse(datetimestring, null, System.Globalization.DateTimeStyles.RoundtripKind);

timeUtc.Kind.ToString() 返回“本地”

那么,我该如何补救呢?时间将发送给我 UTC。

最佳答案

您必须添加 DateTime.SpecifyKind

private static DateTime ConvertToLocalTime(string datetimestring)
{
DateTime timeUtc = DateTime.Parse(datetimestring);
var dt = DateTime.SpecifyKind(timeUtc, DateTimeKind.Utc);
TimeZoneInfo cstZone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
DateTime cstTime = TimeZoneInfo.ConvertTimeFromUtc(dt, cstZone);
return cstTime;
}

.net Fiddle

关于C# ConvertTimeFromUtc 时髦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41819948/

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