C++时间和日期

本文介绍了C++中处理日期和时间的方法,包括如何使用`ctime`库中的关键数据结构和函数,例如`time_t`、`tm`结构体、`time()`、`localtime()`等,并列举了日期和时间格式化字符串的用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C++ Date & Time

Instruction

C++标准库没有提供所谓的日期类型。C++继承了C语言用于日期和时间操作的结构和函数。 
要使用日期和时间相关函数与数据结构,需要`#include <ctime>` 

Data Struct & Function

Data Struct

1. 四个与时间相关的类型: clock_t, time_t, size_t, tm
2. tm struct 

```
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
    int tm_year;     // since 1900
    int tm_wday;     // 0 - 6 (sunday = 0) 
    int tm_yday;     // 0 - 365
    int tm_isdst;    // 夏令时
};
```

Functions

1. time_t time(time_t *time);
2. char *ctime(const time_t *time);              // Eg. Mon Apr 02 10.15.36 2018\n\0
3. struct tm *localtime(const time_t *time);
4. clock_t clock(void);
5. char *asctime(const struct tm *time);         // Eg. Mon Apr 02 10.15.36 2018\n\0
6. struct tm *gmtime(const time_t *time);
7. time_t mktime(struct tm *time);
8. double difftime(time_t time1, time_t time2);
9. size_t strftime(char *str, size_t maxsize, const char *format, const struct tm *timeptr);

10. string time format
    %a      short weekday 
    %A      full weekday 
    %b      short month
    %B      full month
    %c      date and time   Eg. Mon Apr 02 10.15.36 2018 
    %d      month day 
    %H      24h format
    %I      12h format
    %j      year day
    %m      month 01-12
    %M      minutes 00-59
    %p      AM or PM
    %S      second  00-61
    %U      week of year (the first day is sunday)
    %w      weekday 0-6  \
    %W      week of year (the first day is monday)
    %x      date Eg. 08/19/12
    %X      time Eg. 10.15.36
    %y      short year 00-99 (since 1900)
    %Y      full year
    %Z      timezone name
    %%      display a %
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值