如何在 C 或 C++ 中将周数添加到当前时间(现在)

How to add number of weeks to Current Time (Now) in C or C++?

本文关键字:时间 现在 添加 周数 C++      更新时间:2023-10-16

如何在 C 或 C++ 中将周数添加到当前日期?

对于月份部分,即通过使用"ctime.h"中的"difftime"函数将月份添加到当前日期。几个星期以来,它并不是那么微不足道,我正在寻找LOC较少的解决方案。

在这里,此代码查找当前时间和同年 1 月 1 日之间的差异。 我使用与此类似的逻辑来完成将 x 个月添加到当前时间的任务。

#include <stdio.h>      /* printf */
#include <time.h>       /* time_t, struct tm, difftime, time, mktime */
int main ()
{
  time_t now;
  struct tm newyear;
  double seconds;
  time(&now);  /* get current time; same as: now = time(NULL)  */
  newyear = *localtime(&now);
  newyear.tm_hour = 0; newyear.tm_min = 0; newyear.tm_sec = 0;
  newyear.tm_mon = 0;  newyear.tm_mday = 1;
  seconds = difftime(now,mktime(&newyear));
  printf ("%.f seconds since new year in the current timezone.n", seconds);
  return 0;
}

tm_mon将根据我正在寻找的月数设置(我也照顾了一年的轮班)。我不能使用tm_wday做同样的事情。

对于 C++11(引入了<chrono>标头):

#include <chrono>
#include <ctime>
auto now = std::chrono::system_clock::now();
auto nextWeek = now + std::chrono::hours(24*7);
std::time_t nextWeek_time_t = std::chrono::system_clock::to_time_t(nextWeek);

Jan Henke的回答是正确的,我已经投了赞成票。但我想补充一点,最佳做法是让<chrono>为您进行所有单位转换。 在这种情况下,我们没有单位weeks . 但是我们可以很容易地建立一个。

首先创建一个单位days

using days = std::chrono::duration
    <int, std::ratio_multiply<std::ratio<24>, std::chrono::hours::period>>;

这说:

一天有24小时。

现在您已准备好构建weeks

using weeks = std::chrono::duration
    <int, std::ratio_multiply<std::ratio<7>, days::period>>;

一周有7天。

现在,使用weeks(和days)非常简单,就像使用任何其他<chrono>单元一样:

auto now = std::chrono::system_clock::now();
auto nextWeek = now + weeks{1};

如果您想执行诸如计算本地时区自年初以来经过的完整周数之类的操作,则可以使用这个免费的开源C++11/14时区库,该库利用<chrono>库。

#include "tz.h"
#include <chrono>
#include <iostream>
int
main()
{
    using namespace date;
    using namespace std::chrono;
    // Get current timezone
    auto zone = current_zone();
    // Get current system time
    auto now = std::chrono::system_clock::now();
    // Find the current year in the current timezone
    auto local_now = zone->to_local(now);
    auto y = year_month_day{floor<days>(local_now)}.year();
    // Find the system time of the start of the local year
    auto newyear = zone->to_sys(local_days{y/jan/1});
    // Get the difference between these two system times, truncated to weeks
    auto diff_weeks = floor<weeks>(now - newyear);
    std::cout << diff_weeks.count() << 'n';
}

只是为我输出:

15

如果您不关心考虑本地时区,您可以通过简单地计算 UTC 中的所有内容来做到这一点:

#include "date.h"
#include <chrono>
#include <iostream>
int
main()
{
    using namespace date;
    using namespace std::chrono;
    // Get current system time
    auto now = std::chrono::system_clock::now();
    // Find the current year
    auto y = year_month_day{floor<days>(now)}.year();
    // Find the time of the start of the year
    sys_days newyear = y/jan/1;
    // Get the difference between these two system times, truncated to weeks
    auto diff_weeks = floor<weeks>(now - newyear);
    std::cout << diff_weeks.count() << 'n';
}

也只是输出:

15