您的位置:首页 > 其它

时间与字符串之间的转换

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: