linux localtime


#include <stdio.h>
#include <time.h>
#include <sys/time.h>

int main(void)
{
    time_t tNow = time(NULL);
    printf("tNow %ld\n",tNow);
    struct tm* ptnow = localtime(&tNow);


    char szTmp[64] = {0};
    strftime(szTmp, sizeof(szTmp), "%H:%M:%S",ptnow);
    printf("szTmp %s\n",szTmp);

    time_t tEnd = tNow + 360;
    struct tm* ptend = localtime(&tEnd);
    strftime(szTmp, sizeof(szTmp), "%H:%M:%S",ptend);
    printf("szTmp %s\n",szTmp);


    struct timeval tv1;
    gettimeofday(&tv1,NULL);
    sleep(3);
    struct timeval tv2;
    gettimeofday(&tv2,NULL);
    printf("tv1 %ld\n",tv1.tv_sec);
    printf("tv2 %ld\n",tv2.tv_sec);

    return 0;
}



修改下localtime的位置

#include <stdio.h>
#include <time.h>
#include <sys/time.h>

int main(void)
{
    time_t tNow = time(NULL);
    printf("tNow %ld\n",tNow);
    struct tm* ptnow = localtime(&tNow);
    time_t tEnd = tNow + 360;
    struct tm* ptend = localtime(&tEnd);

    char szTmp[64] = {0};
    strftime(szTmp, sizeof(szTmp), "%H:%M:%S",ptnow);
    printf("szTmp %s\n",szTmp);

    strftime(szTmp, sizeof(szTmp), "%H:%M:%S",ptend);
    printf("szTmp %s\n",szTmp);//same as before


    struct timeval tv1;
    gettimeofday(&tv1,NULL);
    sleep(3);
    struct timeval tv2;
    gettimeofday(&tv2,NULL);
    printf("tv1 %ld\n",tv1.tv_sec);
    printf("tv2 %ld\n",tv2.tv_sec);

    return 0;
}


       The localtime() function converts the calendar time timep to broken-down time representation, expressed relative to the user's specified timezone.  The return value points to a statically allocated struct which might be overwritten by  sub‐sequent calls to any of the date and time functions.  The localtime_r() function does the same, but stores the data in a user-supplied struct.


查阅localtime的文档,发现这段话:

This structure is statically allocated and shared by the functions gmtime and localtime. Each time either one of these functions is called the content of this structure is overwritten.

也就是说每次只能同时使用localtime()函数一次,要不就会被重写!

The localtime() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

因此localtime()不是可重入的。同时libc里提供了一个可重入版的函数localtime_r();

Unlike localtime(), the reentrant version is not required to set tzname。


这点跟inet_ntoa是一样的

点击查看

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值