【问题标题】:How to get seconds into human readable dates如何将秒数转换为人类可读的日期
【发布时间】:2018-09-09 09:39:03
【问题描述】:

我正在尝试将表示自 1970 年 1 月 1 日以来秒数的任意整数值转换为人类可读的日期。

这是我得到的最接近的日期,但我一直得到当前日期。如何获取不是当前日期的struct tm

#include <iostream> 
#include <string>
#include <time.h>

using namespace std;

int main() {
  struct tm * timeStruct;
  time_t myTime = 946684800; //s from 1970 to 2000
  int timeStamp = time(&myTime); //I thought this would set the date to the values of myTime, it just sets it to now
  timeStruct = localtime(&myTime);
  cout << timeStamp;
  cout << "\n";
  cout << asctime(timeStruct); //This should read Jan 1, 2000, instead it keeps giving me the current time
  cout << "\n";
  system("pause");
  return 0;
}

【问题讨论】:

  • 那是因为time 返回当前时间。不支持您尝试使用它的方式。
  • gmtimemktime 可能对您有帮助吗?
  • @Sneftel 我已经编辑了我的标题以更准确地反映问题。我担心我得到的答案会曲解我的意图。

标签: c++ time


【解决方案1】:

time(&amp;myTime) 将 myTime 的值设置为当前时间(这显然是意料之中的)。

解决方案:

#include <iostream> 
#include <string>
#include <time.h>

using namespace std;

int main() {
  struct tm * timeStruct;
  time_t myTime = 946684800; //s from 1970 to 2000

  int timeStamp = myTime;
  timeStruct = localtime(&myTime);

  cout << timeStamp;

  cout << "\n";

  cout << asctime(timeStruct);

  cout << "\n";

  system("pause");

  return 0;
}

【讨论】:

  • time_t 也以秒为单位,而不是毫秒。你做得对,但评论说ms有点令人困惑。
  • C++ 不保证 time_t 值表示自 1970 年以来的秒数。您的代码不可移植。
  • “显然”? en.cppreference.com/w/cpp/chrono/c/time - time - 返回编码为 std::time_t 对象的当前日历时间,并将其存储在 arg 指向的对象中"
  • @john 这是我自己的内部工具之一,所以这对我来说并不重要......但是。有没有很好的便携解决方案?
  • @GlenPierce 我不知道。你可以试试Boost.Date_Time
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-24
  • 2018-12-02
  • 2010-09-15
  • 2021-02-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多