C语言下的连续时间戳转换标准格式

一、首先要介绍的是:

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 才能得到不同的时间戳对应的标准格式时间。

四、下面开始介绍

  1. 创建time_t s = atol(你的时间戳字符串);
  2. 创建struct tm *stime = (struct tm *)calloc(1, sizeof(struct tm));
  3. 使用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);
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值