通过查看源码分析
namespace std
{using ::clock_t; // clock_t x; X = clock(); //获取程序跑了多久using ::time_t; // time_t y; y = time(NULL); //从纪元开始计算 相当于程序从1970年开始跑// 获取当前时间 time_t current_time; //current_time = time(NULL); //或者 time(¤t_time); 当然也会返回 函数返回值也会可以是当前时间using ::tm; //结构体 包含秒、分、时、天1(月)、月、天2(星期)、年份差(基准为1900)、天(年)、夏令 其实可以简单理解为本地时间using ::clock;using ::difftime; //返回两个时间戳的差 time_t x, y; difftime(x, y);using ::mktime; //将tm结构时间转换为时间戳using ::time; using ::asctime; //将tm结构时间转换为stringusing ::ctime; //将时间戳转换为字符串using ::gmtime; using ::localtime;using ::strftime; //将tm 结构体按照指定format格式输出为string
} // namespace#include <stdio.h>
#include <time.h>
#include <string>int main() {time_t current_time;struct tm *utc_timeinfo;time(¤t_time); // 获取当前时间戳 时间戳格式:月 日 当前时间 年份std::string nowTime = ctime(¤t_time);printf("nowTime :%s\n", nowTime.c_str());utc_timeinfo = gmtime(¤t_time); // 转换为 UTC 时间结构printf("UTC time: %s", asctime(utc_timeinfo));//本地模式utc_timeinfo = localtime(¤t_time);std::string tmNowTime = asctime(utc_timeinfo);printf("localTime Mode :%s", tmNowTime.c_str());//指定格式char time_str[80];strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", utc_timeinfo);printf("strftime :%s", time_str);return 0;
}//一些占位符的补充
%X %x 十六进制 分别以大写、小写表示
%llx long long 大小的占位符 过短会被截断
%p 专输出地址 占位符
//
参考:
占位符参考