linux c设置系统时间函数,Linux C 中获取local日期和时间 time()&localtime()函数

#include #define _DATETIME_SIZE 32

// GetDate - 获取当前系统日期

/**

* 函数名称:GetDate

* 功能描述:取当前系统日期

*

* 输出参数:char * psDate - 系统日期,格式为yyymmdd

* 返回结果:0 -> 成功

*/

int GetDate(char * psDate)

{

time_t nSeconds;

struct tm * pTM;

time(&nSeconds); // 同 nSeconds = time(NULL);

pTM = localtime(&nSeconds);

/* 系统日期,格式:YYYMMDD */

sprintf(psDate,"%04d-%02d-%02d",

pTM->tm_year + 1900, pTM->tm_mon + 1, pTM->tm_mday);

return 0;

}

// GetTime - 获取当前系统时间

/**

* 函数名称:GetTime

* 功能描述:取当前系统时间

*

* 输出参数:char * psTime -- 系统时间,格式为HHMMSS

* 返回结果:0 -> 成功

*/

int GetTime(char * psTime)

{

time_t nSeconds;

struct tm * pTM;

time(&nSeconds);

pTM = localtime(&nSeconds);

/* 系统时间,格式: HHMMSS */

sprintf(psTime, "%02d:%02d:%02d",

pTM->tm_hour, pTM->tm_min, pTM->tm_sec);

return 0;

}

// GetDateTime - 取当前系统日期和时间

/**

* 函数名称:GetDateTime

* 功能描述:取当前系统日期和时间

*

* 输出参数:char * psDateTime -- 系统日期时间,格式为yyymmddHHMMSS

* 返回结果:0 -> 成功

*/

int GetDateTime(char * psDateTime)

{

time_t nSeconds;

struct tm * pTM;

time(&nSeconds);

pTM = localtime(&nSeconds);

/* 系统日期和时间,格式: yyyymmddHHMMSS */

sprintf(psDateTime, "%04d-%02d-%02d %02d:%02d:%02d",

pTM->tm_year + 1900, pTM->tm_mon + 1, pTM->tm_mday,

pTM->tm_hour, pTM->tm_min, pTM->tm_sec);

return 0;

}

// 测试代码

int main()

{

int ret;

char DateTime[_DATETIME_SIZE];

memset(DateTime, 0, sizeof(DateTime));

/* 获取系统当前日期 */

ret = GetDate(DateTime);

if(ret == 0)

printf("The Local date is %s

", DateTime);

else

perror("GetDate error!");

memset(DateTime, 0, sizeof(DateTime));

/* 获取当前系统时间 */

ret = GetTime(DateTime);

if(ret == 0)

printf("The Local time is %s

", DateTime);

else

perror("GetTime error!");

memset(DateTime, 0, sizeof(DateTime));

/* 获取系统当前日期时间 */

ret = GetDateTime(DateTime);

if(ret == 0)

printf("The Local date and time is %s

", DateTime);

else

perror("GetDateTime error!");

return 0;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值