1

我有一个始终保持午夜时间的日期时间列表,以及当天网站被认为“启动”的秒数。

我需要计算出“正常运行时间”的百分比,所以我需要确切知道那天有多少秒。我想知道.NET 中是否有任何类似于 DateTime.DaysInMonth(year, month) 但一天中的秒数的东西。

我的 Google-fu 似乎让我失望了,我能找到的只是.NET 在一天中的秒数不变?- 但这没有考虑夏令时。

我认为这很简单

var secondsInDay = (startDay.AddDays(1) - startDay).TotalSeconds;

但我想知道这是否正确(简单但并非详尽的测试表明它是正确的)?
有没有更有效的方法来计算一天中的秒数?

请注意 - 这需要考虑夏令时

4

3 回答 3

1

我认为您需要使用DateTimeOffsetand TimeZoneInfo。本文可以帮助您,特别是使用 DateTimeOffset 值的比较和算术运算部分的第二个代码片段。

您可以在该代码中看到他们在夏令时向 DateTimeOffset 实例添加小时数,并且结果考虑了时间变化。

编辑:下面的代码取自上面提到的文章(代码没有做你想要的,但表明DateTimeOffset使用的TimeZoneInfo是考虑夏令时:

    public static void Main()
   {
      DateTime generalTime = new DateTime(2008, 3, 9, 1, 30, 0);
      const string tzName = "Central Standard Time";
      TimeSpan twoAndAHalfHours = new TimeSpan(2, 30, 0);

      // Instantiate DateTimeOffset value to have correct CST offset 
      try
      {
         DateTimeOffset centralTime1 = new DateTimeOffset(generalTime, 
                    TimeZoneInfo.FindSystemTimeZoneById(tzName).GetUtcOffset(generalTime));

         // Add two and a half hours      
         DateTimeOffset centralTime2 = centralTime1.Add(twoAndAHalfHours);
         // Display result
         Console.WriteLine("{0} + {1} hours = {2}", centralTime1, 
                                                    twoAndAHalfHours.ToString(), 
                                                    centralTime2);  
      }
      catch (TimeZoneNotFoundException)
      {
         Console.WriteLine("Unable to retrieve Central Standard Time zone information.");
      }
   }

    // The example displays the following output to the console: 
    //    3/9/2008 1:30:00 AM -06:00 + 02:30:00 hours = 3/9/2008 4:00:00 AM -06:00
于 2013-04-05T20:58:41.247 回答
0

这个怎么样:

TimeSpan.FromDays(1).TotalSeconds

当然,除非您试图计算一天中偶尔添加和删除的秒数,以使地球进动与时钟保持一致

对于日光跟踪,您可以检查您的一天是否是返回的两个日期之一

TimeZone.CurrentTimeZone.GetDaylightChanges(2013)

并添加/删除 Delta

或者您可以通过始终根据过去 24 小时而不是 1 天计算正常运行时间来跳过这些恶作剧

于 2013-04-05T20:56:53.840 回答
0

这是一个可以满足您要求的功能:

public int SecondsInDay(DateTime dateTime, string timeZoneId)
{
    var dt1 = dateTime.Date;
    var dt2 = dt1.AddDays(1);
    var zone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);

    var dto1 = new DateTimeOffset(dt1, zone.GetUtcOffset(dt1));
    var dto2 = new DateTimeOffset(dt2, zone.GetUtcOffset(dt2));
    var seconds = (dto2 - dto1).TotalSeconds;

    return (int) seconds;
}

举个例子:

int s = SecondsInDay(new DateTime(2013, 1, 1), "Central Standard Time");
// 86400

int s = SecondsInDay(new DateTime(2013, 3, 10), "Central Standard Time");
// 82800

int s = SecondsInDay(new DateTime(2013, 11, 3), "Central Standard Time");
// 90000
于 2013-04-05T22:26:49.203 回答