Unix时间戳转换date time格式

2017-07-29

unix 时间戳(unix timestamp) 也叫unix时间(unix time),是unix系统,类unix系统的一种时间表示方式,指的是:从格林威治时间1970年01月01日00时00分00秒起至现在的总秒数。
Note: 内核版本比较低的Linux系统由于将Unix时间戳存储为32位,它能被表示的最后时间是2038年1月19日03:14:07(UTC),因此会导致2038年问题。
Unix时间戳有10位(秒级),也有13位(毫秒级),也有19位(纳秒级)等。
eg.

1
2
3
unix time: 1501292159 # 秒级:10位
可以转换成
date time: 2017/7/29 9:35:59

首先来看下我们下面要用到的两种数据类型的定义:
unix time: time_t
date time: struct tm

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// time_t 定义
typedef __time32_t time_t;
typedef __int32 __time32_t;
// tm 结构定义
struct tm {
int tm_sec; /* seconds after the minute - [0,59] */
int tm_min; /* minutes after the hour - [0,59] */
int tm_hour; /* hours since midnight - [0,23] */
int tm_mday; /* day of the month - [1,31] */
int tm_mon; /* months since January - [0,11] */
int tm_year; /* years since 1900 */
int tm_wday; /* days since Sunday - [0,6] */
int tm_yday; /* days since January 1 - [0,365] */
int tm_isdst; /* daylight savings time flag */
};

下面给出用c++实现的两种时间格式的相互转换:

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
/*
* Learn to transform unix time step to datetime
*/
#include <iostream>
#include <ctime>
const std::string weekdays[] = {
"Sunday", "Monday","Tuesday","Wendsday","Thursday","Friday","Saturday"
};
tm unix_2_datetime(time_t unix_time) {
// transform unxi time to date time
auto tick = (time_t) unix_time; // if your input is long long: change it to 'time_t' first
struct tm tm_ = *localtime(&tick);
return tm_;
}
time_t datetime_2_unix(tm date_time) {
// tranform date time to unix time
time_t unix_time = mktime(&date_time);
return unix_time;
}
void learn_struct_tm(const tm date_time) {
std::cout<<"\n#: Some members of struct 'tm': "<<std::endl;
std::cout<<"> weekday: "<<weekdays[date_time.tm_wday]<<std::endl;
std::cout<<"> hour: "<<date_time.tm_hour<<std::endl;
std::cout<<"> min: "<<date_time.tm_min<<std::endl;
}
int main() {
// get current unix time
time_t unix_time;
time(&unix_time);
// transform between unix time and date time
tm date_time = unix_2_datetime(unix_time);
unix_time = datetime_2_unix(date_time);
std::cout<<"#: Time format transform: "<<std::endl;
std::cout<<"> date time is: "<<asctime(&date_time);
std::cout<<"> unix time is: "<<unix_time<<std::endl;
// more usage about struct tm
learn_struct_tm(date_time);
return 0;
}

运行结果:

1
2
3
4
5
6
7
8
#: Time format transform:
> date time is: Sat Jul 29 10:22:44 2017
> unix time is: 1501294964
#: Some members of struct 'tm':
> weekday: Saturday
> hour: 10
> min: 22