日期与时间(C/C++)

C++继承了C语言用于日期和时间操作的结构和函数,使用之前程序要引用<ctime>头文件

有四个与时间相关的类型:clock_t、time_t、size_t、和tm。类型clock_t、size_t、和time_t能够把系统时间和日期表示为某种整数。

结构体tm把时间和日期以C结构的形式保存,tm结构的定义如下:

struct tm
{
    int tm_sec; //秒,正常范围0 ~59,但是允许到61
    int tm_min; //分 范围 0~59
    int tm_hour; //小时 0~23
    int tm_mday;    //一月中的第几天
    int tm_mon;    //月 0~11
    int tm_year;    //自1900年起的年数
    int tm_wday;    //一周中的第几天
    int tm_yday;    //一年中的第几天
    int tm_isdst; //夏令时    
}

相关函数:

函数

描述

time_t time(time_t *time);

该函数返回系统的当前日历时间。自1970年1月1日以来经过的秒数,如果系统没有时间,返回-1

char *ctime(const time_t *time);

该函数返回一个表示当地时间的字符串指针,字符串形式day month year hours:minutes:seconds year

struct tm *localtime(const time_t *time);

该函数返回一个指向表示本地时间的tm结构的指针。

clock_t clock(void);

该函数返回程序执行起,处理器时间所使用的时间,如果时间不可用,则返回-1

char *asctime(const struct tm *time);

该函数返回一个指向字符串的指针,字符串包含了time所指向结构中存储的信息,返回的形式为:day month year hours:minutes:seconds year

struct tm *gmtime(const time_t *time);

该函数返回一个指向time的指针,time为tm结构,用协调世界时(UTC)也被称为格林尼治标准时间(GMT)表示

time_t mktime(struct tm *time);

该函数返回日历时间,相当于time所指向结构中存储的时间

double difftime(time_t time2,time_t time1);

该函数返回time1和time2之间相差的秒数

size_t strftime();

该函数可用于格式化日期和时间为指定的格式

实例:

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

int main()
{
    //基于当前系统日期和时间 初始化0
    time_t now = time(0);

    /把now转换成字符串形式
    char *dt = ctime(&now);

    cout << "local date and time:  " << dt << endl;

    //把now转化成tm结构
    tm *gmtm = gmtime(&now);
    dt = asctime(gmtm);
    cout << "UTC date and time :  " << dt << endl;
    return 0;
}

运行结果:

exbot@ubuntu:~/wangqinghe/C++/time$ ./time

local date and time:  Mon Aug  5 14:54:25 2019

UTC date and time :  Mon Aug  5 06:54:25 2019

使用结构体tm格式化时间

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

int main()
{
    time_t now = time(0);
    
    cout << "from 1970  then the seconds passed : " << now << endl;

    tm* ltm = localtime(&now);

    cout << "year : " << 1900 + ltm->tm_year << endl;
    cout << "month : " << 1 + ltm->tm_mon << endl;
    cout << "day : " << ltm->tm_mday << endl;
    cout << "hour : " << ltm->tm_hour << ":";
    cout << ltm->tm_min << ":";
    cout << ltm->tm_sec << endl;
    return 0;
}

运行结果:

exbot@ubuntu:~/wangqinghe/C++/time$ ./time1

from 1970  then the seconds passed : 1564988067

year : 2019

month : 8

day : 5

hour : 14:54:27

以20xx-xx-xx xx:xx:xx格式输出结果:

#include<iostream>
#include<ctime>
#include<cstdlib>
#include<cstdio>

using namespace std;

string Get_Current_Date();

int main()
{
    cout << Get_Current_Date().c_str() << endl;
    return 0;
}

string Get_Current_Date()
{
    time_t nowtime;
    nowtime = time(NULL);
    char tmp[64];
    strftime(tmp,sizeof(tmp),"%Y-%m-%d %H:%M:%S",localtime(&nowtime));
    return tmp;
}

运行结果:

exbot@ubuntu:~/wangqinghe/C++/time$ ./time2

2019-08-05 15:00:14

原文地址:https://www.cnblogs.com/wanghao-boke/p/11305023.html