localtime函数和strftime函数

本文介绍了localtime函数,该函数用于将从1970年至今的秒数转换为本地时间。同时详细讲解了strftime函数,它可以根据指定格式将时间格式化。文章通过示例代码展示了这两个函数的具体应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

localtime函数

功能:

把从1970-1-1零点零分到当前时间系统所偏移的秒数时间转换为本地时间,而gmtime函数转换后的时间没有经过时区变换,是UTC时间 。

用法:

#include <time.h>

struct tm *localtime(const time_t *clock);

返回值:

指向tm 结构体的指针, tm结构体是time.h中定义的用于分别存储时间的各个量(年月日等)的结构体.

 

strftime函数

功能:

根据区域设置,格式化本地时间/日期,功能就是将时间格式化

用法:

#include <time.h>

size_t strftime(char * strDest,  size_t maxszie, const char * format,  const struct tm*  timeptr);

 

 

示例如下:

#include <stdio.h>
#include <unistd.h>
#include <time.h>

int main(void)
{
   char ct[80];
   time_t  tt;
   struct tm *tblock;

   tt = time(NULL);
   tblock = localtime(&tt);

   printf("Local time is %s\n", asctime(tblock));

   strftime(ct, sizeof(ct), "%Y-%m-%d %H:%M:%S", tblock);
   printf("now is %s\n", ct);

   return 0;
}

 

结果:

 

备注:

strftime函数常使用的formate参数:

specifierReplaced byExample
%aAbbreviated weekday name *Thu
%AFull weekday name *Thursday
%bAbbreviated month name *Aug
%BFull month name *August
%cDate and time representation *Thu Aug 23 14:55:02 2001
%dDay of the month (01-31)23
%HHour in 24h format (00-23)14
%IHour in 12h format (01-12)02
%jDay of the year (001-366)235
%mMonth as a decimal number (01-12)08
%MMinute (00-59)55
%pAM or PM designationPM
%SSecond (00-61)02
%UWeek number with the first Sunday as the first day of week one (00-53)33
%wWeekday as a decimal number with Sunday as 0 (0-6)4
%WWeek number with the first Monday as the first day of week one (00-53)34
%xDate representation *08/23/01
%XTime representation *14:55:02
%yYear, last two digits (00-99)01
%YYear2001
%ZTimezone name or abbreviationCDT
%%% sign%

转载于:https://www.cnblogs.com/rohens-hbg/p/7921344.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值