localtime函数和strftime函数
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参数:
| specifier | Replaced by | Example |
|---|---|---|
| %a | Abbreviated weekday name * | Thu |
| %A | Full weekday name * | Thursday |
| %b | Abbreviated month name * | Aug |
| %B | Full month name * | August |
| %c | Date and time representation * | Thu Aug 23 14:55:02 2001 |
| %d | Day of the month (01-31) | 23 |
| %H | Hour in 24h format (00-23) | 14 |
| %I | Hour in 12h format (01-12) | 02 |
| %j | Day of the year (001-366) | 235 |
| %m | Month as a decimal number (01-12) | 08 |
| %M | Minute (00-59) | 55 |
| %p | AM or PM designation | PM |
| %S | Second (00-61) | 02 |
| %U | Week number with the first Sunday as the first day of week one (00-53) | 33 |
| %w | Weekday as a decimal number with Sunday as 0 (0-6) | 4 |
| %W | Week number with the first Monday as the first day of week one (00-53) | 34 |
| %x | Date representation * | 08/23/01 |
| %X | Time representation * | 14:55:02 |
| %y | Year, last two digits (00-99) | 01 |
| %Y | Year | 2001 |
| %Z | Timezone name or abbreviation | CDT |
| %% | A % sign | % |

浙公网安备 33010602011771号