C++入门:日期&时间

C++ 标准库没有提供所谓的日期类型。C++ 继承了 C 语言用于日期和时间操作的结构和函数。为了使用日期和时间相关的函数和结构,需要在 C++ 程序中引用 <ctime> 头文件。

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

20**-**-** **:**:** 格式输出当前日期:

#include <iostream>
#include <ctime>
#include <stdlib.h>
#include <stdio.h>

using namespace std;

string  Get_Current_Date();

int main( )
{
    // 将当前日期以 20** - ** - ** 格式输出
    cout << Get_Current_Date().c_str() << endl;

    getchar();
    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;
}

输出格式类似:

2018-09-19 09:00:58

vs2017 上使用安全方法:

#include <iostream>
#include <ctime>

using namespace std;

#define TIMESIZE 26

int main() {
    // 时间
    time_t now = time(0);
    char dt[TIMESIZE];
    errno_t err;
    err = ctime_s(dt, TIMESIZE, &now);
    cout << "local time: " << dt << endl;
    cout << "timestamp: " << now << endl;
    struct tm ltm;
    localtime_s(<m, &now);
    cout << "年: " << 1900 + ltm.tm_year << endl;
    cout << "月: " << 1 + ltm.tm_mon << endl;
    cout << "日: " << ltm.tm_mday << endl;
    cout << "时间: " << ltm.tm_hour << ":";
    cout << ltm.tm_min << ":";
    cout << ltm.tm_sec << endl;
    return 0;
}

例 1 本地时间和格林威治时间安全的写法:

#include <iostream>
#include <ctime>

using namespace std;

int main()
{
    struct tm tmnow;
    char dt[100];

    // 基于当前系统的当前日期/时间
    time_t now = time(0);

    // 把 now 转换为字符串形式
    ctime_s(dt,100,&now);

    cout << "本地日期和时间:" << dt << endl;

    // 把 now 转换为 tm 结构
    gmtime_s(&tmnow,&now);
    asctime_s(dt ,&tmnow);
    cout << "UTC 日期和时间:" << dt<< endl;
}

在VS 2013中运行此程序会出现如下错误:

1>error C4996: 'ctime': This function or variable may be unsafe. Consider using ctime_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.

========== 生成: 成功 0 个,失败 1 个,最新 0 个,跳过 0 个 ==========

查阅之后,发现加入#pragma warning(disable : 4996)【如果您确定代码中没有安全问题,可以通过禁用此功能#pragma warning(disable : 4996)。】

之后就可以了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

灰度少爷

加个鸡腿🍗

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值