#include <time.h>
time_t time(time_t *t); //获取当前的系统时间,其值表示从1970年1月1日00:00:00到当前时刻的秒数。
time_t t;
t = time(NULL);
time(&t);
struct tm *localtime(const time_t *t); //把从1970-1-1零点零分到当前时间系统所偏移的秒数时间转换为本地时间。
struct tm
{
int tm_sec; /* seconds range 0-59*/
int tm_min; /* minutes range 0-59*/
int tm_hour; /* hours range 0-23*/
int tm_mday; /* day of the month range 1-31*/
int tm_mon; /* month range 0-11*/ 从 0 开始表示一月
int tm_year; /* year */ 从 1900 开始
int tm_wday; /* day of the week range 0-6*/ 星期数从 0(星期天)到 6(星期六)
int tm_yday; /* day in the year range 0-365*/
int tm_isdst; /* daylight saving time */
};
time_t mktime(struct tm *tm); //把本地时间转换成秒
例:
#include <stdio.h>
#include <time.h>
int main()
{
time_t t;
struct tm *p;
t = time(NULL);
p = localtime(&t);
printf("%d-%d-%d %d:%d:%d\n",p->tm_year + 1900,p->tm_mon + 1,p->tm_mday,p->tm_hour,p->tm_min,p->tm_sec);
}
size_t strftime(char *s, size_t max, const char *format, const struct tm *tm);//将一个tm结构格式化为一个字符串
例:
#include <stdio.h>
#include <time.h>
int main()
{
time_t t;
struct tm *p;
char buf[256];
t = time(NULL);
p = localtime(&t);
strftime(buf,256,"%Y-%m-%d %H:%M:%S",p);
printf("%s\n",buf);
}
char *strptime(const char *s, const char *format, struct tm *tm);//将一个字符串格式化为一个tm结构
例:
#include <stdio.h>
#include <time.h>
int main()
{
time_t t;
struct tm tm;
char buf[]="2014-08-23 23:00:12";
strptime(buf,"%Y-%m-%d %H:%M:%S",&tm);
t = mktime(&tm);
printf("%ld\n",t);
}
转载于:https://blog.51cto.com/liuzhanwei/1543439