【CPP】⏰ 时间处理

Simple Demo

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <time.h>
using namespace std;

int main()
{
time_t t;
time(&t);
cout << t <<endl;
return 0;
}

以上代码会输出一个10位数,表示的是到当前时间的秒数,起点是 1970年1月1日 00:00:00

time_t 转换

  1. stringtime_t

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    time_t StringToDatetime(std::string str)
    {
    char *cha = (char*)str.data(); // 将string转换成char*。
    tm tm_; // 定义tm结构体。
    int year, month, day, hour, minute, second;// 定义时间的各个int临时变量。
    sscanf(cha, "%d-%d-%d %d:%d:%d", &year, &month, &day, &hour, &minute, &second);// 将string存储的日期时间,转换为int临时变量。
    tm_.tm_year = year - 1900; // 年,由于tm结构体存储的是从1900年开始的时间,所以tm_year为int临时变量减去1900。
    tm_.tm_mon = month - 1; // 月,由于tm结构体的月份存储范围为0-11,所以tm_mon为int临时变量减去1。
    tm_.tm_mday = day; // 日。
    tm_.tm_hour = hour; // 时。
    tm_.tm_min = minute; // 分。
    tm_.tm_sec = second; // 秒。
    tm_.tm_isdst = 0; // 非夏令时。
    time_t t_ = mktime(&tm_); // 将tm结构体转换成time_t格式。
    return t_; // 返回值。
    }
  2. time_tstring

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    (1)
    time_t t=std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
    std::stringstream ss;
    ss<<std::put_time(std::localtime(&t),"%F %X");
    ss.str();
    (2)
    size_t strftime (char* ptr, size_t maxsize, const char* format,
    const struct tm* timeptr );
    ptr:存储转换结果
    maxsize:复制到ptr的最大字符数,包括结束符'\0'
    format:转换格式,类似printf,可加入其他需要复制过去的字符
    timeptr:时间
    char buf[20];
    tm* local_time = std::localtime(&t);
    strftime(buf,sizeof(buf),"%F %X",local_time);

C++时间类

使用C++时间类处理获取系统当前时间 日期和时间工具 - C++中文 - API参考文档 (apiref.com)

头文件 #include <chrono>

  1. 获取当前时间
1
system_clock::time_point now = std::chrono::system_clock::now();
  1. 将当前时间转换为time_格式
1
time_t tt = std::chrono::system_clock::to_time_t(now);
  1. 将time_格式的时间转换为tm *格式
1
struct tm* tmNow = localtime(&tt);
  1. 将tm*格式的时间转换为可读的时间
1
2
char date[20] = { 0 };
sprintf(date, "%d-%02d-%02d %02d:%02d:%02d",(int)tmNow->tm_year + 1900, (int)tmNow->tm_mon + 1, (int)tmNow->tm_mday, (int)tmNow->tm_hour, (int)tmNow->tm_min, (int)tmNow->tm_sec);

最后,在C++中的话可以将char*字符串转换为std::string字符串来处理

1
std::string timeNow(date);

【CPP】⏰ 时间处理
https://hodlyounger.github.io/B_Code/CPP/【CPP】时间处理/
作者
mingming
发布于
2023年10月27日
许可协议