2660|1

659

帖子

1

TA的资源

纯净的硅(中级)

楼主
 

LPCOpen的rtc_ut.c的闰年BUG与解决 [复制链接]

本帖最后由 mars4zhu 于 2015-4-10 15:36 编辑

LPCOpenrtc_ut.c的闰年BUG与解决
在使用LPCOpenrtcut例程时,发现计算日期与实际日期相差一天。
为查找原因,做了一下测试,发现RTCUT之间的转换有误差,

  1. struct tm testTime;
  2. uint32_t testCounter = 0;

  3. /* Convert tm structure to RTC tick count */
  4. ConvertTimeRtc(&startTime, &rtcCount);
  5. ConvertRtcTime(rtcCount, &testTime);
  6. ConvertTimeRtc(&testTime, &testCounter);
  7. ConvertRtcTime(testCounter, &testTime);
  8. ConvertTimeRtc(&testTime, &testCounter);
  9. ConvertRtcTime(testCounter, &testTime);
  10. ConvertTimeRtc(&testTime, &testCounter);
  11. ConvertRtcTime(testCounter, &testTime);
  12. ConvertTimeRtc(&testTime, &testCounter);
  13. ConvertRtcTime(testCounter, &testTime);
  14.    
复制代码

testTimetestCounter之间相互转换,发现每次相互转换后,都会相差一天。

深入探究rtc_ut的源代码,发现其错误在对闰年判断上。

原来的代码判断闰年方式仅仅是能被4整除就是闰年,

  1. /* Leap year check for less than 1 year time */
  2. if ((year % 4) == 0) {
  3. curLeapYear = 1;
  4. }
  5. else {
  6. curLeapYear = 0;
  7. }
复制代码

而刚好使用1900年作为基准年,错误地将1900年当做了闰年,使得在对rtc->ut转换中,多算了一天,而ut->rtc中,却没有将1900年的这一年计算进入,从而每次相互转换时,会造成一天的误差。
而正确的判断闰年方法是:
能被四整除的且不能被100整除的为闰年,能被100整除的,必须也能被400整除才是闰年。
这就是通常所说的:四年一闰,百年不闰,四百年再闰。 例如,2000年是闰年,1900年则是平年。



改正后的代码如下:@note 将rtc_ut.c代码中的(year%4)==0全部替换成isLeapYear(year)即可。

  1. /**
  2. * @brief test if it is a leap year
  3. * @param year        :  the year to test, 1998, 2015
  4. * @return true if the year is leap, else false
  5. * @note replace the code "(year%4) == 0" with "isLeapYear(year)"
  6. */
  7. bool isLeapYear(int year)
  8. {
  9.         if ((year%100) == 0) {
  10.                 if ((year%400) == 0)
  11.                         return true;
  12.                 else
  13.                         return false;
  14.         }
  15.         else {
  16.                 if ((year%4 == 0))
  17.                         return true;
  18.                 else
  19.                         return false;               
  20.         }
  21. }
复制代码




此帖出自NXP MCU论坛

最新回复

很仔细啊  详情 回复 发表于 2015-4-10 17:31

赞赏

1

查看全部赞赏

点赞 关注(1)
 

回复
举报

7671

帖子

2

TA的资源

五彩晶圆(高级)

沙发
 
很仔细啊
此帖出自NXP MCU论坛
 
个人签名

默认摸鱼,再摸鱼。2022、9、28

 
 

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

查找数据手册?

EEWorld Datasheet 技术支持

相关文章 更多>>
关闭
站长推荐上一条 1/9 下一条

 
EEWorld订阅号

 
EEWorld服务号

 
汽车开发圈

About Us 关于我们 客户服务 联系方式 器件索引 网站地图 最新更新 手机版

站点相关: 国产芯 安防电子 汽车电子 手机便携 工业控制 家用电子 医疗电子 测试测量 网络通信 物联网

北京市海淀区中关村大街18号B座15层1530室 电话:(010)82350740 邮编:100190

电子工程世界版权所有 京B2-20211791 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号 Copyright © 2005-2025 EEWORLD.com.cn, Inc. All rights reserved
快速回复 返回顶部 返回列表