代码之家  ›  专栏  ›  技术社区  ›  User987

通过特定方式将datetime设置为特定日期

  •  0
  • User987  · 技术社区  · 6 年前

    我有一个日期时间变量,我必须根据这些规则和场景在特定日期设置:

    • 我连接到的API有一个每日限制,一旦达到该限制,我就必须等到第二天上午9:10 CEST<=这非常重要

    所以我只是这么做:

      var localTime = TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time"));
      var tomorrowAt0910 = localTime.AddDays(1).Date + new TimeSpan(9, 10, 0);
    

    我意识到这段代码有一个bug,因为我可以有以下场景:

    • 假设我的申请将于7月30日下午15:00到期,在这种情况下,上面的逻辑将是有效的

    但是

    我们有一个更可能发生的下一个场景:

    • 申请将于7月31日上午5:00到期,在这种情况下,这种逻辑是错误的,因为续签日期将被设置为8月1日上午9:10,这是错误的

    如果在第二种情况下申请过期,我应该将日期设置为同一天和几个小时的时间差(从早上5点到9点)

    我怎么能这样做?

    2 回复  |  直到 6 年前
        1
  •  3
  •   Jon Skeet    6 年前

    听起来你真正想说的是:

    • 在中欧找到当前时间
    • 找同一天上午9:10
    • 如果上午9:10在当前时间之后,则添加一天

    比如说:

    // No need to do this more than once
    private static readonly TimeZoneInfo centralEuropeZone = 
        TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time")
    
    private static DateTime GetUtcResetTime()
    {
        // Using UtcNow to make it clear that the system time zone is irrelevant
        var centralEuropeNow = TimeZoneInfo.ConvertTime(DateTime.UtcNow, centralEuropeZone);
        var centralEuropeResetTime = centralEuropeNow.Date + new TimeSpan(9, 10, 0);
        if (centralEuropeResetTime <= centralEuropeNow)
        {
            centralEuropeResetTime = centralEuropeResetTime.AddDays(1);
        }
        return TimeZoneInfo.ConvertTimeToUtc(centralEuropeResetTime, centralEuropeZone);
    }
    

    我已经做了回报 协调世界时 DateTime 所以没有其他代码需要担心它在哪个区域。

        2
  •  1
  •   VDWWD    6 年前

    检查到期日期是否小于当前日期,如果是,则添加一天。

    DateTime expireDate = new DateTime(2018, 7, 30, 22, 0, 0); //for testing
    
    DateTime tomorrowAt0910 = DateTime.Now.Date.AddHours(9).AddMinutes(10);
    
    if (expireDate.Date < DateTime.Now.Date)
    {
        tomorrowAt0910.AddDays(1);
    }