在C ++中获取截止到本年年初的UTC时期时间

问题描述 投票:0回答:1

我正在尝试获取今年年初的EPOCH时间(无区域差异的通用时间)。以下是我写的内容:

    time_t getEpochTimeAtSOY(){
        /* Get the current year */
        time_t currTime = time(NULL);
        struct tm *aTime = localtime(&currTime);
        int currentYear = aTime->tm_year;   // This is (actualCurrentYear - 1900), so 2020 - 1900 = 120

        /* Now find out EPOCH time for start of currentYear */
        struct tm t;
        time_t timeSinceEpoch = 0;
        memset (&t, 0, sizeof(t));  // Initalize to all 0's
        t.tm_year = currentYear;
        t.tm_mday = 1;

        timeSinceEpoch = timegm(&t); // EPOCH time of 1st Jan <currentYear> 00:00

        return (timeSinceEpoch);
    }

这将在x86或x86_64上返回正确的结果(即1577836800),但是目标板(交叉编译器)不支持timegm()函数。如果我使用mktime()代替timegm(),则会导致区域时差。有人可以建议其他便携式解决方案吗?也许使用std :: chrono或其他?

c++ time epoch chrono
1个回答
3
投票

[我刚刚意识到,getEpochTimeFromSOY()旨在仅返回与第一年相关的time_t,而不是在当前时间与第一年之间进行减法运算。这是:

std::time_t
getEpochTimeFromSOY()
{
    using namespace date;
    using namespace std::chrono;
    auto currTime = system_clock::now();
    auto y = year_month_day{floor<days>(currTime)}.year();
    return floor<seconds>(sys_days{y/1/1} - sys_days{})/1s;
}

[这在C ++ 20中非常容易,并且有一个库可以使用C ++ 20语法来做到这一点,并且可以追溯到C ++ 11(使用chrono)。

这是C ++ 20语法:

#include <ctime>
#include <chrono>

std::time_t
getEpochTimeFromSOY()
{
    using namespace std::chrono;
    auto currTime = system_clock::now();
    auto y = year_month_day{floor<days>(currTime)}.year();
    return floor<seconds>(currTime - sys_days{y/1/1})/1s;
}

Here's the header-only, free, open-source library that you can use prior to C++20,这是使用它的语法:

#include "date/date.h"

#include <ctime>
#include <chrono>

std::time_t
getEpochTimeFromSOY()
{
    using namespace date;
    using namespace std::chrono;
    auto currTime = system_clock::now();
    auto y = year_month_day{floor<days>(currTime)}.year();
    return floor<seconds>(currTime - sys_days{y/1/1})/1s;
}

即包括date.h并添加using namespace date

代码说明:

  • 获取当前时间作为system_clock::time_point
  • 以UTC获取当前时间的年份。
  • 从当前时间中减去一年中的第一时间(UTC),将其截断为秒精度,然后除以1秒以得出计数。

语法1s在C ++ 14中引入。在C ++ 11中,您可以将其更改为seconds{1}。或者,您可以将/1s替换为.count()以提取秒作为整数类型。

如果您不想使用免费的开放源代码库来执行此操作,则可以获取underlying algorithms from here并自己进行编码。

© www.soinside.com 2019 - 2024. All rights reserved.