C 将日期时间转换为时间戳

C++ converting datetime to timestamp

本文关键字:时间戳 转换 时间 日期      更新时间:2023-10-16

我知道这些值

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 byte。

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并进行操纵。

您的问题也在这里解决。

也许最简单,最高的性能是使用霍华德·辛南特(Howard Hinnant

#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

此库扩展了<chrono>库来处理日历计算,甚至是为标准化而提出的。

这就是我的方式,它可以接受更多的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>();
}
#include <iostream>
#include <string>
#include <chrono>
#include <sstream>
#include <iomanip>
const std::string timeFormat{"%Y%m%d %H:%M:%S"};
int64_t getTimeStamp(const std::string& timeString)
{
    std::istringstream m_istream{timeString};
    std::tm m_tm { 0 };
    std::time_t m_timet { 0 };
    m_istream >> std::get_time(&m_tm, timeFormat.c_str());
    m_timet = std::mktime(&m_tm);
    m_timet *= 1000; // convert to milliseconds
    return m_timet;
}
int main() {
    const std::string timeString{ "20220509 10:07:38" };
    int64_t result = getTimeStamp(timeString);
    std::cout << "result:" << result << std::endl;
    return 0;
}