时间与字符串之间的转换
2016-01-06 23:06
295 查看
#include <cstdio>
#include <ctime>
#include <string>
using namespace std;
//time_t到tm的转换
struct tm time_to_tm(time_t t)
{
struct tm* ans = localtime(&t);
return *ans;
}
//tm到time_t的转换
time_t tm_to_time(struct tm t)
{
return mktime(&t);
}
//tm到str的转换
string tm_to_str(struct tm t)
{
char s[50];
string ans;
strftime(s, 50, "%Y-%m-%d %H:%M:%S", &t);
ans = s;
return ans;
}
//time_t到str的转换
string time_to_str(time_t t)
{
struct tm tmp = time_to_tm(t);
return tm_to_str(tmp);
}
//str到tm的转换
int str_to_tm(string s, struct tm& t)
{
char *p = strptime(s.c_str(), "%Y-%m-%d %H:%M:%S", &t);
if (NULL == p) return -1;
return 0;
}
//str到time_t的转换
int str_to_time(string s, time_t& t)
{
struct tm tmp;
if (str_to_tm(s, tmp)) return -1;
t = tm_to_time(tmp);
return 0;
}
int main()
{
time_t now = time(NULL);
printf("now:%d\n", now);
string s = time_to_str(now);
printf("str:%s\n", s.c_str());
str_to_time(s, now);
printf("now:%d\n", now);
s = time_to_str(now);
printf("str:%s\n", s.c_str());
return 0;
}
#include <ctime>
#include <string>
using namespace std;
//time_t到tm的转换
struct tm time_to_tm(time_t t)
{
struct tm* ans = localtime(&t);
return *ans;
}
//tm到time_t的转换
time_t tm_to_time(struct tm t)
{
return mktime(&t);
}
//tm到str的转换
string tm_to_str(struct tm t)
{
char s[50];
string ans;
strftime(s, 50, "%Y-%m-%d %H:%M:%S", &t);
ans = s;
return ans;
}
//time_t到str的转换
string time_to_str(time_t t)
{
struct tm tmp = time_to_tm(t);
return tm_to_str(tmp);
}
//str到tm的转换
int str_to_tm(string s, struct tm& t)
{
char *p = strptime(s.c_str(), "%Y-%m-%d %H:%M:%S", &t);
if (NULL == p) return -1;
return 0;
}
//str到time_t的转换
int str_to_time(string s, time_t& t)
{
struct tm tmp;
if (str_to_tm(s, tmp)) return -1;
t = tm_to_time(tmp);
return 0;
}
int main()
{
time_t now = time(NULL);
printf("now:%d\n", now);
string s = time_to_str(now);
printf("str:%s\n", s.c_str());
str_to_time(s, now);
printf("now:%d\n", now);
s = time_to_str(now);
printf("str:%s\n", s.c_str());
return 0;
}
相关文章推荐
- 史上最牛逼的纯CSS实现tab选项卡,闪瞎你的狗眼
- 9个常用iptables配置实例
- bzoj2594 水管局长数据加强版
- 仿锤子系统的垃圾扫描的自定义View
- 在android 中导入项目后 包出现错误
- Android输入法界面管理(打开/关闭/状态获取)
- 前端开发入门:前端构建工具百度FIS
- 找出两链表的交点
- clientHeight / scrollHeight / offsetHeight 等属性的区别图
- Git的基础
- [OJ] Insert Interval
- 14-mysql优化之使用存储过程向mysql数据库中添加4000000条数据
- JavaScript 操作 Cookie
- Iteration Vs Recursion Java
- 大数据系列第五课:scala基础
- 知识累积——这些年写过的博文
- MATLAB画图
- JAVA之Switch语句
- #ifdef DEBUG的理解
- [Andrid转]新版安卓SDK文件activity_main.xml和fragment_main.xml的处理