基础知识:
函数:
time(NULL)
time(NULL)
会返回当前时间的 Unix 时间戳,即从1970年1月1日00:00:00到当前时刻的秒数。这是一个整数,表示当前的时间点。
localtime
/ localtime_s
将一个 time_t
类型的时间戳转换为本地时间,返回一个 tm
结构体。
localtime_s
是线程安全的版本。
示例代码:
time_t now = time(NULL);
tm local_tm;
localtime_s(&local_tm, &now); // 使用线程安全的版本
asctime_s
asctime_s(chars, 100, &timeForm);
asctime_s
会将 tm
结构中的本地时间转换为一个标准格式的字符串(例如:Thu Dec 11 15:21:16 2024
),chars
用来存放转换后的字符串,大小为100字节
注意:asctime_s
输出的格式是固定的,包括星期、月份、日期、时间和年份。
strftime
使用 tm
结构体格式化输出日期和时间,生成一个指定格式的字符串
char buffer[80];
strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", &local_tm);
// 输出格式为:2024-12-11 15:21:16
数据类型:
tm
tm是 C/C++ 标准库中用于表示时间的一个结构体,定义在 <time.h>
头文件中。它用来存储本地时间的各个组成部分,如年、月、日、时、分、秒等。结构体 tm
通常在处理时间和日期时作为参数或返回值,特别是在处理 time_t
类型的时间戳时。
在 <time.h>
中,tm
结构体通常定义如下:
struct tm {
int tm_sec; // 秒,范围: 0-59
int tm_min; // 分,范围: 0-59
int tm_hour; // 小时,范围: 0-23
int tm_mday; // 日,范围: 1-31
int tm_mon; // 月,范围: 0-11(0 = 一月,1 = 二月,...)
int tm_year; // 年,表示自1900年以来的年份(例如:2024年就是 2024 - 1900 = 124)
int tm_wday; // 星期几,范围: 0-6(0 = 周日,1 = 周一,...)
int tm_yday; // 年中的第几天,范围: 0-365
int tm_isdst; // 夏令时标志,正值表示启用夏令时,0表示不启用,负值表示信息不可用
};
time_t
time_t
在 <time.h>
或 <ctime>
头文件中,time_t
是一个用于存储时间的标量类型。它通常是一个整数或长整型(long
或 long long
),具体取决于平台的实现。它的值表示的是自 "Unix 纪元"(1970年1月1日00:00:00 UTC)以来的秒数。
time_t nowTime = time(NULL);//获取时间戳
用法:
基本用法示例:
#include <iostream>
#include<time.h>
using namespace std;
int main()
{
time_t nowTime = time(NULL);//获取时间戳
tm timeForm;
char chars[100];
localtime_s(&timeForm ,&nowTime);//将时间戳转换为本地时间
//将本地时间转换为字符串放在chars中
//方法一:输出全部的时间信息
asctime_s(chars,100,&timeForm);
//方法二:输出自定义格式的时间 %a星期几,%b月份,%d日,%Y年份, %H:%M:%S:小时:分钟:秒
strftime(chars, sizeof(chars), "%H:%M:%S", &timeForm);
cout << chars;
}
获取毫秒级的时间示例
long GetTimeMs()
{
// 获取当前时间点
auto now = std::chrono::system_clock::now();
// 转换为自纪元以来的毫秒数
auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
std::cout << "当前时间的毫秒级时间戳: " << millis << std::endl;
}
自定义函数:
获取时间
可直接赋值时间给字符串
#include <iostream>
#include<time.h>
using namespace std;
//获取时间
void GetTime(string& timeString)
{
time_t nowTime = time(NULL);//获取时间戳
tm timeForm;
char chars[100];
localtime_s(&timeForm, &nowTime);//将时间戳转换为本地时间
strftime(chars, sizeof(chars), "%Y %H:%M:%S", &timeForm); //格式化到chars中
timeString = string(chars);//强制转化为string类型
}
int main()
{
string timeString;
GetTime(timeString);
cout << timeString;
}
计算时间差
可计算两个时分秒格式的时间差
//函数重载:time1-time2
int operator-(string time1, string time2)
{
int h1 = stoi(time1.substr(5, 2));//时
int h2 = stoi(time2.substr(5, 2));
int m1 = stoi(time1.substr(8, 2));//分
int m2 = stoi(time2.substr(8, 2));
int s1 = stoi(time1.substr(11, 2));//秒
int s2 = stoi(time2.substr(11, 2));
int sAll1 = 3600 * h1 + 60 * m1 + s1;
int sAll2= 3600 * h2 + 60 * m2 + s2;
int c= sAll1-sAll2;
return c;
}