【问题标题】:C++ converting datetime to timestampC ++将日期时间转换为时间戳
【发布时间】:2017-09-04 09:10:43
【问题描述】:

我知道这些价值观

unsigned char year = 17; // means 2017
unsigned char month = 8;
unsigned char day = 25;
unsigned char hour = 14;
unsigned char minute = 23;
unsigned char second = 54; 

如何将这些转换为 unix 时间戳?我不确定unsigned char 是否是表示值的正确方法,我只需要每个值的大小为 1 字节。

【问题讨论】:

  • 如果你有 unsigned char year = 99; 是指 2099 年还是 1999 年?
  • 我只需要现在和未来的时间。所以意思是2099,一般是year + 2000
  • edit 把你的问题说清楚那里
  • 你可能需要this
  • Howard answer 应该被标记为正确答案,因为它是真正的 C++ 解决方案。他的日期库实际上会进入C++20standard

标签: c++ datetime


【解决方案1】:

Ubervan回答了你的问题

将日期分解为其组成部分,即日、月、年,然后:

struct tm  tm;
time_t rawtime;
time ( &rawtime );
tm = *localtime ( &rawtime );
tm.tm_year = year - 1900;
tm.tm_mon = month - 1;
tm.tm_mday = day;
mktime(&tm);

现在可以将 tm 转换为 time_t 并进行操作。

here也解决了您的问题。

【讨论】:

  • 也许你应该把你的完整答案放在这里。链接可能会失效。
【解决方案2】:

也许最简单和性能最高的方法是使用Howard Hinnant's free, open-source, header-only datetime library

#include "date.h"
#include <iostream>

date::sys_seconds
to_sys_time(unsigned char y, unsigned char m, unsigned char d,
            unsigned char h, unsigned char M, unsigned char s)
{
    using namespace date;
    using namespace std::chrono;
    return sys_days{year{y+2000}/m/d} + hours{h} + minutes{M} + seconds{s};
}

int
main()
{
    std::cout << to_sys_time(17, 9, 25, 14, 23, 54).time_since_epoch().count() << '\n';
}

这个输出:

1503671034

这个库扩展了&lt;chrono&gt; 库来处理日历计算,它是even being proposed for standardization

【讨论】:

    【解决方案3】:

    这就是我将采用更多 c++ 11 的方式。

    std::string timepointToString(std::chrono::system_clock::time_point const& t) {
      time_t tt = std::chrono::system_clock::to_time_t(t);
      struct tm tb;
      size_t const len(21);
      char buffer[len];
      TRI_gmtime(tt, &tb);
      ::strftime(buffer, sizeof(buffer), "%Y-%m-%dT%H:%M:%SZ", &tb);
      return std::string(buffer, len - 1);
    }
    
    std::chrono::system_clock::time_point stringToTimepoint(std::string const& s) {
      if (!s.empty()) {
        try {
          std::tm tt;
          tt.tm_year = std::stoi(s.substr(0, 4)) - 1900;
          tt.tm_mon = std::stoi(s.substr(5, 2)) - 1;
          tt.tm_mday = std::stoi(s.substr(8, 2));
          tt.tm_hour = std::stoi(s.substr(11, 2));
          tt.tm_min = std::stoi(s.substr(14, 2));
          tt.tm_sec = std::stoi(s.substr(17, 2));
          tt.tm_isdst = 0;
          auto time_c = TRI_timegm(&tt);
          return std::chrono::system_clock::from_time_t(time_c);
        } catch (...) {}
      }
      return std::chrono::time_point<std::chrono::system_clock>();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-25
      • 2022-01-08
      • 1970-01-01
      • 2020-10-19
      • 2016-11-26
      相关资源
      最近更新 更多