C++ datetime calculation api
来源:互联网 发布:基础算法面试题 编辑:程序博客网 时间:2024/06/05 08:51
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
0 0
- C++ datetime calculation api
- datetime.c
- C#DateTime
- c#DateTime
- Java8 new datetime api
- Joda DateTime API
- Calculation
- C#DateTime函数
- C#DateTime函数
- DateTime类型[C#]
- c datetime 格式化
- C#DateTime各种使用
- 登山c#-datetime说明
- 【C#】DateTime格式大全
- 关于C#-DateTime值
- C#DateTime字符串格式化
- C#DateTime操作全解
- String Format for DateTime [C#]
- 集合的特殊功能之TreeSet集合如何保证元素的唯一及排序的
- jsp的隐式对象
- 华为上机考试注意事项及编程技巧(精品)
- 详解for/while循环的各种用法
- Linux grub引导修复
- C++ datetime calculation api
- 1.mongoDB的windows安装过程
- (二)python 基础教程
- 写一个宏将一个数字的奇数位和偶数位交换
- Git使用(二)
- Data too long for column 'filecontent' at row 1
- 安卓中ViewPager控件的使用
- JAVA基础知识
- C++ call dlopen function