0

我想在 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;
4

1 回答 1

0

将 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 小时,此功能将不起作用,并且需要一个日期参数。

于 2021-07-06T14:19:52.170 回答