LoginSignup
2
0

More than 5 years have passed since last update.

VC++でUnix時間をローカル時間にするコード

Posted at

現在のUnix時間(UTC 1970 年 1 月 1 日からの経過秒数を表す)を、Fri Mar 8 15:17:26 2019みたいな時間に変換して出力するコード。
こちらによると、localtime_sasctime_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

参考にした記事

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0