使用strptime、strftime进行时间字符串与时间结构struct tm之间的转换
struct tm {
int tm_sec; /* Seconds (0-60) */
int tm_min; /* Minutes (0-59) */
int tm_hour; /* Hours (0-23) */
int tm_mday; /* Day of the month (1-31) */
int tm_mon; /* Month (0-11) */
int tm_year; /* Year - 1900 */
int tm_wday; /* Day of the week (0-6, Sunday = 0) */
int tm_yday; /* Day in the year (0-365, 1 Jan = 0) */
int tm_isdst; /* Daylight saving time */
};
头文件:
#include <time.h>
---将时间字符串转换为tm
char *strptime(const char *s, const char *format, struct tm *tm);
s:时间字符串,如:2017-10-20 12:32 、 17:23
format:时间格式
tm:struct tm结构
return: NULL表示转换失败
---将tm转化为时间字符串
size_t strftime(char *s, size_t max, const char *format, const struct tm *tm);
s:结果缓存
max:最大长度限制
format:转化格式
tm:tm结构
return:0 error
(备注:若编译是出现如下错误:
changetime.c: In function ‘main’:
changetime.c:16:12: warning: implicit declaration of function ‘strptime’ [-Wimplicit-function-declaration]
if( ( p = strptime("2017-05-23 5:32:12", "%Y-%m-%d %H:%M:%S", &tim) ) != NULL ) {
^
changetime.c:16:10: warning: assignment makes pointer from integer without a cast [-Wint-conversion]
if( ( p = strptime("2017-05-23 5:32:12", "%Y-%m-%d %H:%M:%S", &tim) ) != NULL ) {
在编译选项上加上-D_GNU_SOURCE -D__USE_XOPEN即可)
例:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
int
main(void)
{
struct tm tim;
char *p = NULL;
char buf[100];
int size;
memset(&tim, 0, sizeof(struct tm));
if( ( p = strptime("2017-05-23 5:32:12", "%Y-%m-%d %H:%M:%S", &tim) ) != NULL ) {
printf("year:%d\n", tim.tm_year + 1900);
printf("month:%d\n", tim.tm_mon + 1);
printf("day:%d\n", tim.tm_mday);
printf("hour:%d\n", tim.tm_hour);
printf("minute:%d\n", tim.tm_min);
printf("second:%d\n", tim.tm_sec);
} else {
printf("strptime error!\n");
}
if( strftime(buf, sizeof(buf) - 1, "%Y-%m-%d %H:%M:%S", &tim) != 0 ) {
printf("time:%s\n", buf);
} else {
printf("strftime error!\n");
}
return 0;
}