我是靠谱客的博主 苹果航空,这篇文章主要介绍【C/C++业务】UNIX时间戳与正常时间相互转换,现在分享给大家,希望可以做个参考。

正常时间转UNIX时间 与 UNIX时间转正常时间

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #include <string> #include <iostream> using namespace std; //str : 20201030 int time2unix(string str) { struct tm time; time_t t; if (str.length() != 8) return 0; time.tm_year = atoi(str.substr(0, 4).c_str()) - 1900; /* 年份修正 */ time.tm_mon = atoi(str.substr(4, 2).c_str()) - 1; /* 月份修正 */ time.tm_mday = atoi(str.substr(6, 2).c_str()); time.tm_hour = 0; time.tm_min = 0; time.tm_sec = 0; t = mktime(&time); return (int)t; } string unix2time(int n,int format) { char s[100] = {0}; memset(s, 0, 100); time_t tick = (time_t)(n); struct tm *tm = localtime(&tick); switch (format) { case TIEM_TYPE_DATE: //DATA: 20201030 strftime(s, sizeof(s), "%Y%m%d", tm); break; default: //TIME: 2020-10-30 10:10:10 strftime(s, sizeof(s), "%Y-%m-%d %H:%M:%S", tm); break; } return string(s); } int main() { string ret; string str = "20200131"; int a = 0; a = time2unix(str); cout << a << endl; if (a == 0) ret = unix2time(a); else { a += 86400; ret = unix2time(a); } cout << ret << endl; }

有时候unix时间戳会以16进制形式存在,先将16进制转成10进制

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int hex_to_dec(char* a) { int len = strlen(a); int sum = 0; for (int i = 0; i < len; i++) { if (a[i] >= 'A' && a[i] <= 'F') { a[i] = int(a[i] - 'A') + 10 + '0'; } if (a[i] >= 'a' && a[i] <= 'f') { a[i] = int(a[i] - 'a') + 10 + '0'; } sum += (a[i] - '0') * (pow(16.0, len - 1 - i)); } return sum; }

参考博客:

UNIX时间戳和北京时间的相互转换

Unix时间戳和北京时间的相互转换(C语言实现 )

最后

以上就是苹果航空最近收集整理的关于【C/C++业务】UNIX时间戳与正常时间相互转换的全部内容,更多相关【C/C++业务】UNIX时间戳与正常时间相互转换内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(64)

评论列表共有 0 条评论

立即
投稿
返回
顶部