C++ datetime calculation api


Description


A sample of how use C++ localtime/mktime to implement datetime calculation, for example plus/minus a few days, months, years, etc.


Source Code:

#include <time.h>
#include <iomanip>

#include <iostream>

void printtm(const char * prefix, tm * tp) {
    std::cout << prefix;
    std::cout << std::setw(4) << std::setfill('0') << tp->tm_year + 1900;   // year
    std::cout << "/";
    std::cout << std::setw(2) << std::setfill('0') << tp->tm_mon + 1;   // month
    std::cout << "/";
    std::cout << std::setw(2) << std::setfill('0') << tp->tm_mday;  // day
    std::cout << " ";
    std::cout << std::setw(2) << std::setfill('0') << tp->tm_hour;  // hour
    std::cout << ":";
    std::cout << std::setw(2) << std::setfill('0') << tp->tm_min;   // minute
    std::cout << ":";
    std::cout << std::setw(2) << std::setfill('0') << tp->tm_sec;   // second
    std::cout << std::endl;
}

int main(int argc, char * argv[]) {
    time_t t = time(NULL);
    tm * tp = localtime(&t);
 
    printtm("today     :", tp);
    tp->tm_mday += 2; mktime(tp);
    printtm("+2 days   :", tp);  // 2 days later
    tp->tm_mon  += 2; mktime(tp);
    printtm("+2 months :", tp);  // 2 months later
    tp->tm_year -= 2; mktime(tp);
    printtm("-2 year   :", tp);  // 2 years before
    return 0;
}



Compile and execute:

$ g++ tt.cpp 
$ ./a.out 
today     :2015/12/29 04:16:25
+2 days   :2015/12/31 04:16:25
+2 months :2016/03/02 04:16:25
-2 year   :2014/03/02 04:16:25


Limitation:

Function localtime() is not thread-unsafe, it uses an internal memory space to keep the datetime data structure, when multiply calling localtime(..) they overwrite the same memory space.

So localtime() cannot be shared among multiply threads.



The end


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值