如何使秒成为人类可读的日期

时间:2018-09-09 09:39:03

标签: c++ time

我正在尝试将代表自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;
}

1 个答案:

答案 0 :(得分:0)

time(&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;
}