LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 1255|回复: 1

秒转换成UTC的时间格式,为何差了十天?

[复制链接]
发表于 2009-6-10 01:46:47 | 显示全部楼层 |阅读模式
时间:2009/6/9/ 17/36/11
为什么刚刚好差10天呢?

printf:

  1. 1244568971
  2. 2009
  3. 6
  4. 19
  5. 17
  6. 36
  7. 11
复制代码

  1. #define IsLeapYear(y) ((!(y % 4)) ? (((!(y % 400)) && (y % 100)) ? 1 : 0) : 0)
  2. #define LEAPY (366*24*60*60)
  3. #define COMMONY (365*24*60*60)
  4. #define DAYINSECS (24*60*60)
  5. int main()
  6. {
  7.   struct timeval tm;
  8.   time_t itm;
  9.   int i,j;
  10.   int month,sec;
  11.   int dtmp,htmp,mtmp;
  12.   int mds[12]={31,28,31,30,31,30,31,31,30,31,30,31};

  13.   gettimeofday(&tm,NULL);

  14.   itm = tm.tv_sec;
  15.   for(i=1970;;i++)
  16.     {
  17.       if(IsLeapYear(i) && (itm >= LEAPY))
  18.         itm -= LEAPY;
  19.       else if(!IsLeapYear(i) && (itm>=COMMONY))
  20.         itm -= COMMONY;
  21.       else
  22.         break;
  23.     }

  24.   month = 1;
  25.   for(j=0;j<12;j++)
  26.     {
  27.       if( (month==2) && IsLeapYear(i) && (itm>=(28*DAYINSECS)) )
  28.         {
  29.           itm-=(29*DAYINSECS);
  30.           month=month+1;
  31.         }
  32.       else if( itm>=mds[j]*DAYINSECS )
  33.         {
  34.           itm-=(mds[j]*DAYINSECS);
  35.           month=month+1;
  36.         }
  37.       else
  38.         break;
  39.     }

  40.   dtmp = itm/(DAYINSECS);
  41.   itm -= dtmp*DAYINSECS;
  42.   htmp = itm/(60*60);
  43.   itm -= htmp*60*60;
  44.   mtmp = itm/60;
  45.   sec = itm%60;

  46.   printf("%d\n",tm.tv_sec);
  47.   printf("%d\n",i);
  48.   printf("%d\n",month);
  49.   printf("%d\n",dtmp);
  50.   printf("%d\n",htmp);
  51.   printf("%d\n",mtmp);
  52.   printf("%d\n",sec);
  53.   return 0;
  54. }

复制代码
 楼主| 发表于 2009-6-10 08:59:29 | 显示全部楼层
原来是这个判断有误。。。
  1. #define IsLeapYear(y) ((!(y % 4)) ? (((!(y % 400)) && (y % 100)) ? 1 : 0) : 0)
复制代码
  1. #define IsLeapYear(y) (((y%400 == 0) || (y%4 == 0) && (y%100 != 0)) ? 1 : 0)
复制代码
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表