【问题标题】:Get total seconds between 2 times获取 2 次之间的总秒数
【发布时间】:2021-09-17 03:50:24
【问题描述】:

我想在 Arduino 中实现这个功能

uint32_t GetSeconds(int hour_now, int minutes_now, int seconds_now,
                    int hour_future, int minutes_future, int seconds_future);

类似这样,但不使用相关日期:

uint32_t future = DateTime(2021, 1, 1, 16, 0, 0).unixtime();
DateTime now = rtc.now();
uint32_t timestamp = now.unixtime();
uint32_t seconds_to_sleep = future - timestamp;

【问题讨论】:

  • 全部转换为秒:uint32_t now = hour_now * 3600 + minutes_now * 60 + seconds_now。对未来做同样的事情并减去。请注意,如果未来时间超过午夜,这将不起作用。为此,您将需要一些额外的代码。
  • 谢谢你,约翰尼,但“请注意,如果未来时间超过午夜,这将不起作用”是问题所在,这就是日期(数字)的来源......
  • 如果未来时间超过 24 小时,此功能将不起作用,需要一个日期参数。是否保证少于 24 小时?

标签: c++ arduino arduino-esp8266 arduino-c++ arduino-esp32


【解决方案1】:

将 h,m,s 转换为秒并减去。处理未来已过午夜的特殊情况。在这种情况下,添加从午夜开始的每个时间的差异。

// Helper function
uint32_t hms_to_seconds(int hour, int minutes, int seconds)
{
    return hour * 3600 + minutes * 60 + seconds;
}

uint32_t GetSeconds(int hour_now, int minutes_now, int seconds_now,
                    int hour_future, int minutes_future, int seconds_future)
{
    uint32_t now = hms_to_seconds(hour_now, minutes_now, seconds_now);
    uint32_t future = hms_to_seconds(hour_future, minutes_future, seconds_future;

    // Future is not past midnight
    if (now < future) {
        return future - now;
    }
    // Future is past midnight
    else {
        uint32_t midnight = hms_to_seconds(24, 0 , 0);
        return (midnight - now) + future;
    }
}

如果未来时间超过 24 小时,此功能将不起作用,需要一个日期参数。

【讨论】:

  • 未来的时间不会超过 24 小时,所以这段代码对我来说可以正常工作,感谢您的宝贵时间,非常感谢...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多