【发布时间】:2023-04-07 05:19:01
【问题描述】:
我有一些数据点,其中包括与 gmt 的偏移量(以秒为单位)。我想在午夜通过套接字发送消息。发送消息没问题,我只是根据偏移量确定时间有困难。
有人对此有什么建议吗?
【问题讨论】:
我有一些数据点,其中包括与 gmt 的偏移量(以秒为单位)。我想在午夜通过套接字发送消息。发送消息没问题,我只是根据偏移量确定时间有困难。
有人对此有什么建议吗?
【问题讨论】:
由于 UTC 和 GMT 相同,您可以使用此代码。
int secondsOffset = 100;
DateTime utcMidnight = DateTime.SpecifyKind(DateTime.Today, DateTimeKind.Utc);
DateTime utcWithOffset = utcMidnight.AddSeconds(secondsOffset);
Console.WriteLine("Offset on UTC: " + utcWithOffset);
Console.WriteLine("Offset on local time: " + utcWithOffset.ToLocalTime());
第一个 WriteLine 显示 UTC 时区的时间。 第二条 Writeline 显示本地时区的时间。 棘手的部分可能是找出基准时间是什么,是今天午夜还是昨天午夜?
【讨论】:
如果您想获得一个以秒为单位的偏移量的当前时间,您可以这样做:
TimeSpan offset = TimeSpan.FromSeconds(offsetInSecondsFromMidnight);
DateTime initial = DateTime.Now.Date; // Midnight, today - for time, the date doesn't really matter, but we want midnight
DateTime timeWithOffset = initial + offset; // This will have the correct time of day now
【讨论】: