通过在C#中添加服务器日期和UTC TimeSpan来获取UTC DateTime [英] Get UTC DateTime by adding server date and UTC TimeSpan in c#
问题描述
我的数据库中有UTC TimeSpan,如下所示
I have UTC TimeSpan in my DB, which I got as following
item.UTCStartTime = new DateTime(item.StartTime.Ticks).ToUniversalTime().TimeOfDay;
现在,我需要当前的UTC日期时间以及我的UTCStartTime.我正在按照以下步骤进行操作,但似乎提供了错误的时间.
Now I need current UTC DateTime along with my UTCStartTime. I am doing it as follows, but it seems to be providing wrong time.
DateTime time = DateTimeHelper.ConvertUTCToCurrentTimeZone(new DateTime(item.UTCStartTime.Ticks).ToUniversalTime());
然后我像这样更改上面的行
Then I changed the above line like this
DateTime time = DateTimeHelper.ConvertUTCToCurrentTimeZone(new DateTime()).Add(item.UTCStartTime);
现在,我认为除时间段以外,我得到的时间正确.它显示的是正确答案的反面.例如:PM表示PM,AM表示PM 更新:抱歉,时间显示仍然不正确.
注意: DateTimeHelper.ConvertUTCToCurrentTimeZone()只是一个通过以下方法将UTC转换为所需时区的新日期时间的方法TimeZoneId
NOTE: The DateTimeHelper.ConvertUTCToCurrentTimeZone() is just a method to convert the UTC to a new datetime of a desired timezone by TimeZoneId
推荐答案
首先, new DateTime()
返回一个可以显示为 1/1/0001 12的值:00:00 AM (来源: https://docs.microsoft.com/zh-cn/dotnet/api/system.datetime?view=net-5.0 ).几乎将年,月,日,时,分,秒设置为0.此外,它没有指定时区(本地或UTC)返回,因此将其转换为UTC无效.
First of all, new DateTime()
returns a value that can be displayed as 1/1/0001 12:00:00 AM (source: https://docs.microsoft.com/en-us/dotnet/api/system.datetime?view=net-5.0). Pretty much Year, Month, Day, Hour, Minute, Second set to 0. Also, it is returned without specified timezone (local or UTC), thus converting it to UTC does nothing.
var date = new DateTime();
Console.WriteLine(date);
Console.WriteLine(date.ToUniversalTime());
// Output
01/01/0001 00:00:00
01/01/0001 00:00:00
因此,您的约会肯定会结束.如果您确定 item.UTCStartTime
包含正确的UTC时间,可以将其添加到今天的日期,可以使用以下方法完成:
Because of that, your date will definetly be off. If you are sure, that item.UTCStartTime
contains correct UTC time, add it to today's date, can be done with:
var utcTimeToday = DateTime.UtcNow.Date.Add(item.UTCStartTime);
这篇关于通过在C#中添加服务器日期和UTC TimeSpan来获取UTC DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!