一、首先要介绍的是:
typedef __time_t time_t;
这是用来存储时间戳的类型,其实就是个long
型。
二、其次要介绍的是存储标准格式时间的结构体:
/* ISO C `broken-down time' structure. */
struct tm
{
int tm_sec; /* Seconds. [0-60] (1 leap second) */
int tm_min; /* Minutes. [0-59] */
int tm_hour; /* Hours. [0-23] */
int tm_mday; /* Day. [1-31] */
int tm_mon; /* Month. [0-11] */
int tm_year; /* Year - 1900. */
int tm_wday; /* Day of week. [0-6] */
int tm_yday; /* Days in year.[0-365] */
int tm_isdst; /* DST. [-1/0/1]*/
# ifdef __USE_MISC
long int tm_gmtoff; /* Seconds east of UTC. */
const char *tm_zone; /* Timezone abbreviation. */
# else
long int __tm_gmtoff; /* Seconds east of UTC. */
const char *__tm_zone; /* Timezone abbreviation. */
# endif
};
我们可以使用上面的这个结构体来任意拼接我们需要的时间格式。
三、转换函数:
/* Return the `struct tm' representation of *TIMER
in Universal Coordinated Time (aka Greenwich Mean Time). */
extern struct tm *gmtime (const time_t *__timer) __THROW;
/* Return the `struct tm' representation
of *TIMER in the local timezone. */
extern struct tm *localtime (const time_t *__timer) __THROW;
#if defined __USE_POSIX || __GLIBC_USE (ISOC2X)
/* Return the `struct tm' representation of *TIMER in UTC,
using *TP to store the result. */
extern struct tm *gmtime_r (const time_t *__restrict __timer,
struct tm *__restrict __tp) __THROW;
/* Return the `struct tm' representation of *TIMER in local time,
using *TP to store the result. */
extern struct tm *localtime_r (const time_t *__restrict __timer,
struct tm *__restrict __tp) __THROW;
#endif /* POSIX || C2X */
以gmtime()
和gmtime_r
举例,这两个函数都是将参数__timer
转换成标准格式,但是gmtime()
是不可重入的,gmtime_r
才是可重入的。也就是说,如果你需要连续两次转换不同时间戳,而且你使用的是gmtime
,那么你得到两个结果将是一样的。只有使用gmtime_r
才能得到不同的时间戳对应的标准格式时间。
四、下面开始介绍
- 创建
time_t s = atol(你的时间戳字符串);
- 创建
struct tm *stime = (struct tm *)calloc(1, sizeof(struct tm));
- 使用
localtime_r(&s, stime);
我们可以看到,localtime_r()
这个函数的两个参数
(const time_t *__restrict __timer, struct tm *__restrict __tp)
都是要求的指针类型,第一个参数是time_t*
型,该参数因为只是传递参数,因此,可以直接将非指针类型变量s
直接取地址扔进去,但是第二个参数不可以这样。
/* Return the `struct tm' representation of *TIMER in UTC,
using *TP to store the result. */
阅读上面的提示,第二个参数*TP
是用来存储转换成标准格式之后的数据,因此,该参数就必须要求有已经开辟好的空间!所以只能先calloc
或者malloc
一个空间后,将改指针变量传进函数,这样我们才能得到正确的结果。
下面就是任意拼接了。
printf("%d年-%d月-%d日 %d时%d分%d秒\n", stime->tm_year+1900,stime->tm_mon+1,stime->tm_mday,stime->tm_hour, stime->tm_min, stime->tm_sec);