#include "time.h"
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
/*此函数的功能是返回指定日期是星期几*/
int GetWeekDay(int year,int month,int day)
{
int i,j,count=0;
int Day_Index;
int days[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
int MonthAdd[12] = {0,31,59,90,120,151,181,212,243,273,304,334};
#if 0
for(i = 1;i < month;i++)
count = count + days[i];
#else
count = MonthAdd[month-1];
#endif
count = count + day;
if((year%4 == 0&&year %100 != 0||year % 400 == 0)&& month >= 3)
count += 1;
/* 1900或者1901是没有什么问题的,1900年1月1号是周一,
所以下面return时不用加一。而1901年1月1日日周二,
所以在return时需要加一。年份的选择只是作为一个基准。*/
count = count + (year - 1900) * 365;
for(j = 1900;j < year;j++)
{
if(j % 4 == 0 && j % 100 != 0 || j % 400 == 0)
count++;
}
return ((count) % 7);
}
/*mktime的源码实现,算出了从1970年1月1日开始到现在经过了多少秒*/
static inline unsigned long mkmytime (unsigned int year, unsigned int mon,
unsigned int day, unsigned int hour,
unsigned int min, unsigned int sec)
{
if (0 >= (int) (mon -= 2)){ /**//* 1..12 -> 11,12,1..10 */
mon += 12; /**//* Puts Feb last since it has leap day */
year -= 1;
}
return (((
(unsigned long) (year/4 - year/100 + year/400 + 367*mon/12 + day) +
year*365 - 719499
)*24 + hour /**//* now have hours */
)*60 + min /**//* now have minutes */
)*60 + sec; /**//* finally seconds */
}
int main(int argc, char *argv[])
{
if(argc != 4){
fprintf(stderr, "usage: time year mon day/n");
return 0;
}
time_t now;
struct tm *tmnow;
/*利用mktime和localtime_r返回指定日期是星期几*/
struct tm mytime;
int year,mon,day;
year = atoi(argv[1]);
mon = atoi(argv[2]);
day = atoi(argv[3]);
// now = time((time_t *)0);
time(&now);
tmnow = localtime(&now);
fprintf(stdout, "Now is %d年%d月%d日,星期%d,是第%d天/n",
tmnow->tm_year+1900, tmnow->tm_mon+1, tmnow->tm_mday,
tmnow->tm_wday, tmnow->tm_yday);
fprintf(stdout, "localtime Now is %s/n", asctime(tmnow));
tmnow = gmtime(&now);
fprintf(stdout, "gmtime Now is %s/n", asctime(tmnow));
fprintf(stdout, "WeekDay is %d/n", GetWeekDay(year, mon, day));
/*一定要重新置0才可以。*/
memset(&mytime,0,sizeof(struct tm));
memset(&now,0,sizeof(time_t));
mytime.tm_year = year - 1900;
mytime.tm_mon = mon - 1;
mytime.tm_mday = day;
now = mktime(&mytime);
tmnow = localtime_r(&now,&mytime);
fprintf(stdout, "Now is %d年%d月%d日,星期%d,是第%d天/n",
mytime.tm_year+1900, mytime.tm_mon+1, mytime.tm_mday,
mytime.tm_wday, mytime.tm_yday);
/*利用mktime源码实现*/
memset(&mytime,0,sizeof(struct tm));
memset(&now,0,sizeof(time_t));
now = (time_t)mkmytime(year, mon, day, 24, 0, 0);
tmnow = localtime_r(&now,&mytime);
fprintf(stdout, "Now is %d年%d月%d日,星期%d,是第%d天/n",
mytime.tm_year+1900, mytime.tm_mon+1, mytime.tm_mday,
mytime.tm_wday, mytime.tm_yday);
}