通过日历算法,可以看出 C 标准库的时间库已经能够解决大部分的时间问题,惟一的不足是时间的精度只能达到 秒 级别。对于这个不足可以使用C++的“chrono” 库进行补充
就我个人的经验而言,如果不是进行性能测试,对于精度秒级别足够使用
注意:
asctime ctime gmtime localtime strtime 函数实现的内部都是使用了一个静态变量用于存储计算的结果,然后函数返回这个静态变量的地址
多线程中使用这些函数需要借助锁(或其它同步的工具)
asctime 的实现大致如下:(从asctime的实现,我们可以总结两种编程常用的方法:查表法和函数内的静态变量状态保持法)
char* asctime(const struct tm *timeptr)
{
static const char wday_name[][4] = {
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
};
static const char mon_name[][4] = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
static char result[26];
sprintf(result, "%.3s %.3s%3d %.2d:%.2d:%.2d %d\n",
wday_name[timeptr->tm_wday],
mon_name[timeptr->tm_mon],
timeptr->tm_mday, timeptr->tm_hour,
timeptr->tm_min, timeptr->tm_sec,
1900 + timeptr->tm_year);
return result;
}
/*
* 日历
*/
//#include <chrono>
#include <time.h>
#include <stdio.h>
#include <string.h>
void Calendar(int year) {
const char *s_week = "Sun Mon Tue Wed Thu Fri Sat";
tm day_start;
tm *day;
time_t t;
time_t one_day = 3600 * 24;
char MONTH_YEAR[BUFSIZ];
memset(&t, 0, sizeof(time_t));
memset(&day_start, 0, sizeof(tm));
day_start.tm_year = year-1900;
day_start.tm_mon = 0;
day_start.tm_mday = 1;
t = mktime(&day_start);
int month = -1;
int wday = 0;
do {
day = localtime(&t);
if (day->tm_mon != month) {
if (day->tm_wday) putchar('\n');
strftime(MONTH_YEAR, BUFSIZ, "%b %Y", day);
puts(MONTH_YEAR);
puts(s_week);
month = day->tm_mon;
wday = 0;
}
if (day->tm_wday != wday) {
printf("%*s", 4 * day->tm_wday, " ");
}
printf("%3d ", day->tm_mday);
if (day->tm_wday == 6) putchar('\n');
wday = (day->tm_wday+1) % 7;
t += one_day;
} while(day->tm_mon!=11 || day->tm_mday!=31);
}
int main() {
Calendar(2015);
Calendar(2016);
// int year;
// scanf("%d", &year);
// while (year) {
// Calendar(year);
// scanf("%d", &year);
// }
return 0;
}
/*
* 两个日期相隔的天数
*/
#include <time.h>
#include <stdio.h>
#include <string.h>
int main() {
tm tm1;
tm tm2;
time_t t1;
time_t t2;
const double one_day = 3600 * 24;
memset(&tm1, 0, sizeof(tm));
memset(&tm2, 0, sizeof(tm));
tm1.tm_year = 2014-1900;
tm1.tm_mon = 0;
tm1.tm_mday = 1;
t1 = mktime(&tm1);
tm2.tm_year = 2016-1900;
tm2.tm_mon = 0;
tm2.tm_mday = 1;
t2 = mktime(&tm2);
printf("%.lf day", difftime(t2, t1) / one_day);
return 0;
}
/*
* mktime 可以直接对 tm 结构进行运算
*/
#include <time.h>
#include <stdio.h>
#include <string.h>
int main() {
tm tm1;
time_t t1;
memset(&tm1, 0, sizeof(tm));
tm1.tm_year = 2015-1900;
tm1.tm_mday = 1;
tm1.tm_hour = 24;
t1 = mktime(&tm1);
puts(ctime(&t1));
}