現在のUnix時間(UTC 1970 年 1 月 1 日からの経過秒数を表す)を、Fri Mar 8 15:17:26 2019
みたいな時間に変換して出力するコード。
こちらによると、localtime_s
とasctime_s
が標準関数ではないので、MSVC以外のコンパイラでは通らない。
コード
Source.cpp
#include <iostream>
#include <ctime>
#include "time.h"
//これがないとstd::stringをstd::coutできない
#include <string>
time_t get_unix_time() {
time_t now = std::time(nullptr);
return now;
}
std::string unix_to_local(time_t utc) {
struct tm now;
char result[32];
//utc -> local itme
localtime_s(&now, &utc);
//local time -> char*
asctime_s(result, sizeof(result), &now);
//char* -> std::string
std::string str(result);
return str;
}
int main() {
time_t now = get_unix_time();
std::cout << now << std::endl;
std::cout << unix_to_local(now) << std::endl;
_sleep(10000);
return 0;
}
1552025846
Fri Mar 8 15:17:26 2019