将Unix纪元时间戳的长整数转换为实际日期/时间

问题描述

我尝试找到此问题的答案,但我发现的来源无法正确转换时间。最初,当我从.json网络抓取程序获取时间戳时,我在字符串中包含了时间戳,但希望将其转换为可读的日期/时间。我最近一次进行转换的尝试是将字符串转换为long类型,并将long类型转换为time_t类型,然后使用strftime(),但这不会产生正确的答案。

这是我将字符串转换为long,然后转换为time_t,然后使用strftime()的代码

std::string timeStampToRead(const time_t rawtime)
{
  struct tm *dt;
  char buffer [30];
  dt = localtime(&rawtime);
  strftime(buffer,sizeof(buffer),"%m%d %H%M",dt);
  return std::string(buffer);
}

int main()
{
  std::string epochT = "1604563859000";
  long e = atol(epochT.c_str());
  const time_t rawtime = (const time_t)e;
  std::string time = timeStamptToRead(rawtime);
  return 0;
}

此代码的结果为0808 1703

我也尝试做与上面非常相似的事情,但是将timeStampToRead更改为以下内容

std::string timeStampToRead(const time_t rawtime)
{
  struct tm *dt;
  char buffer [30];
  dt = localtime(&rawtime);
  return asctime(dt);
}

这将返回8月8日星期一17:03:20这也是不正确的

正确答案应该是当地时间2020年11月5日(星期四)8:10:59或2020年11月5日(星期四)1:10:59(不一定是正确的格式,只是正确的月份,日期和时间是重要)

我已经测试了将字符串转换为long的结果,并且可以正常工作,所以我认为错误是将long转换为time_t或使用time_t获取时间的可读格式的过程。在这两个选项中,我认为问题很可能是从long到time_t的转换,但找不到其他方法进行转换。

我希望有一种简单的方法可以直接获取字符串并将其转换,但是我在任何地方都找不到任何信息,所以这就是为什么我将字符串转换为long然后转换为time_t的原因。基本上,我不知道如何将字符串或长unix epoch时间戳转换为time_t,以将其转换为可读格式,或者至少是我假设错误所在的地方。如果有人能指出正确的方向来使此转换代码正常工作,我将不胜感激。

解决方法

进一步挖掘后,我发现了错误并确定了最佳路线

std::string epochT = "1604563859000";
long e atol(epochT.c_str());
const time_t rawtime = e/1000;
struct tm * dt;
dt = localtime(&rawtime);
std::string readable = asctime(dt);

此代码将在for循环内,该循环遍历字符串的向量,因此epochT将取决于向量中的元素和当前元素,但这有效并输出Thu Nov 5 01:10:59的正确答案2020当地时间。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...