【问题标题】:.Net Send message at midnight based on TimeZone?.Net 根据时区在午夜发送消息?
【发布时间】:2023-04-07 05:19:01
【问题描述】:

我有一些数据点,其中包括与 gmt 的偏移量(以秒为单位)。我想在午夜通过套接字发送消息。发送消息没问题,我只是根据偏移量确定时间有困难。

有人对此有什么建议吗?

【问题讨论】:

    标签: .net timezone


    【解决方案1】:

    由于 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 显示本地时区的时间。 棘手的部分可能是找出基准时间是什么,是今天午夜还是昨天午夜?

    【讨论】:

      【解决方案2】:

      如果您想获得一个以秒为单位的偏移量的当前时间,您可以这样做:

      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
      

      【讨论】:

        猜你喜欢
        • 2021-01-13
        • 1970-01-01
        • 1970-01-01
        • 2013-06-13
        • 1970-01-01
        • 1970-01-01
        • 2016-01-13
        • 2020-07-21
        • 1970-01-01
        相关资源
        最近更新 更多