目录

C++ UTC时间戳转化为年月日时分秒

目录

方法

使用<ctime>中的 gmtime 进行转换,输入的 timestamp 格式为 Milliseconds 级别

转换为北京时间需要在UTC基础上加8

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <ctime>
#include <string>

#define CCT (+8)

std::string Stamp2Time(long long timestamp) {
    int ms = timestamp % 1000; //取毫秒
    time_t tick = (time_t)(timestamp / 1000); //转换时间
    struct tm tm;
    char s[40];
    // tm = *localtime(&tick);  // 转换为本地时间
    tm = *gmtime(&tick); // 转换 Convert time_t to tm as UTC time
    tm.tm_hour = tm.tm_hour+CCT; // 转换为北京时间 Beijing (China)
    strftime(s, sizeof(s), "%Y-%m-%d %H:%M:%S", &tm);
    std::string str(s);
    // str = str + " " + std::to_string(ms);
    return str;
}

示例

输入

1680944770500

输出

2023-04-08 17:06:10