C++中的<ctime>函数

1. 前言

<ctime>函数库中提供了丰富的有关时间的函数,使用此函数可以轻松实现日期,计时器,随机数等多种功能。(在使用C语言编写stm32实时时钟时,也需要使用此函数库,只不过C语言用的是<time.h>)

2. 常用的函数(简述)

功能函数/类型作用常见写法
获取当前时间time()返回当前时间戳(秒)time_t t = time(NULL)
时间类型time_t存储时间戳time_t t
转字符串时间ctime()时间戳->字符串cout << ctime(&t)
转本地时间结构loacltime()时间戳->tm结构体tm *lt = localtime(&t)
转UTC时间gmtime()转世界时间tm* gt = gmtime(&t)
结构体转时间戳mktime()tm -> time_ttime_t = mktime(&tm)
时间结构体tm存储年月日时分秒tm t
格式化输出strftime()自定义时间格式strftime(buf, size,”%Y-%m-%d”,lt)
随机种子srand()设计随机种子srand(time(NULL))
简单计时差值计算耗时end-start

3.具体描述

1. 时间戳

常见的时间戳为Unix,就是到目前一共有多少秒,起点:1970年1月1日 00:00:00(UTC)

例如 1774956732就表示从起点到2026-03-31 19:32:12一共用了多少秒。

2.UTC

GMT和UTC的时间基本相等,误差为1秒内。

UTC 背后是原子钟 GMT 是地球转出来的,GMT(格林尼治时间);::<周杰伦不是有首歌里写“我占据 格林威治 守候着你 在时间 标准起点 回忆过去”>

3.time_t

用于时间戳的定义, 其类型为long long,注意如果是很大的日期就会出错

time_t t = 1774956732;

4.tm

tm 用于定义时间结构体

struct tm {
    int tm_year; // 年(从1900开始)
    int tm_mon;  // 月(0~11)
    int tm_mday; // 日
    int tm_hour; // 时
    int tm_min;  // 分
    int tm_sec;  // 秒
};

5.time()

返回当前时间戳

语法:

time_t time(time_t* t);

示例:

#include <iostream>
#include <ctime>
using namespace std;

int main() {
    time_t now = time(NULL);
    cout << now << endl;    //返回当前时间戳
}

6.ctime()

时间戳转字符串

语法:

char* ctime(const time_t* t);

示例:

#include <iostream>
#include <ctime>
using namespace std;

int main() {
    time_t now = time(NULL);
    cout << ctime(&now);    //时间戳转字符串,自动换行
}                           // Tue Mar 31 19:53:29 2026

7.localtime()

返回当地时间

语法:

tm* localtime(const time_t* t);

示例:

#include <iostream>
#include <ctime>
using namespace std;

int main() {
    time_t now = time(NULL);
    tm* lt = localtime(&now);//返回当地时间

    cout << lt->tm_year + 1900 << endl; // 2026
}

8.mktime

将tm转化为时间戳

语法:

time_t mktime(tm* t);

示例:

#include <iostream>
#include <ctime>
using namespace std;

int main() {
    tm t = {};
    t.tm_year = 2026 - 1900;
    t.tm_mon = 3 - 1;
    t.tm_mday = 31;

    time_t ts = mktime(&t);
    cout << ts << endl;
}

9.strftime()

格式化输出时间

语法:

size_t strftime(char* str, size_t maxsize, const char* format, const tm* timeptr);

示例:

#include <iostream>
#include <ctime>
using namespace std;

int main() {
    time_t now = time(NULL);
    tm* lt = localtime(&now);

    char buf[100];
    strftime(buf, sizeof(buf), "%Y %m %d %H:%M:%S", lt);//2026 03 31 20:02:23
    strftime(buf, sizeof(buf), "%-Y %-m %-d %H:%-M:%S", lt);//2026 3 31 20:2:49     在格式化字符前加上 - 就可以小区前导零
    cout << buf << endl;
}

总结:

这里只介绍了一部分常用的函数,但是如果面对很大的函数,那么<ctime>就不适用了,所以有些时候还是要自己写的。(如有错误,欢迎指正)

文末附加内容
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇