Chinaunix首页 | 论坛 | 博客
  • 博客访问: 398937
  • 博文数量: 75
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 645
  • 用 户 组: 普通用户
  • 注册时间: 2015-06-03 18:24
文章分类

全部博文(75)

文章存档

2019年(1)

2018年(20)

2017年(14)

2016年(10)

2015年(30)

分类: LINUX

2018-01-08 21:36:46


点击(此处)折叠或打开

  1. #include <stdio.h>
  2. /*
  3.     计算从
  4. */
  5. unsigned long My_mktime(unsigned int year, unsigned int mon, unsigned int day,
  6.                                 unsigned int hour, unsigned int min, unsigned int second)
  7. {
  8.     unsigned int year_to_day = 0;
  9.     unsigned int mon_to_day = 0;
  10.     unsigned int day_to_day = 0;
  11.     /*把1月和2月当作上一年年底的最后两个月,让3月作为一年的第一个月*/
  12.     if((mon -= 2) <= 0)
  13.     {
  14.         mon += 12;
  15.         year -= 1;
  16.     }

  17.     year_to_day = (year - 1) * 365 + year / 4 - year / 100 + year / 400; //计算给出的年数到公元元年的天数
  18.     mon_to_day = (367 * mon / 12) - 30 + 59; //计算给出的月数转换成天数
  19.     day_to_day = day - 1; //当天不能计算上去,所以要减1
  20.     /*719162是0001年1月1日到1970年1月1日所经历的天数*/
  21.     return (((unsigned long)(((year_to_day + mon_to_day + day_to_day - 719162) * 24 + hour) * 60 + min) * 60) + second);
  22. }


  23. typedef struct{
  24.     unsigned char tm_sec;//00~59
  25.     unsigned char tm_min;//00~59
  26.     unsigned char tm_hour;//00~23
  27.     unsigned char tm_mday;//01~31
  28.     unsigned char tm_mon;//01~12
  29.     unsigned char tm_year;//00~99
  30.     unsigned char tm_week;//00~06 设置rtc时间时,不需要设置tm_week选项,获取rtc时间 时,可以得到一个准确的tm_week值
  31. }date_time_t;

  32. unsigned long Dt_mktime_abs(date_time_t *pTm)
  33. {
  34.     int year/*[2000, 2099]*/ = pTm->tm_year/*[00, 99]*/ + 2000;
  35.     int mon/*[1, 12]*/ = pTm->tm_mon/*[1, 12]*/;
  36.     int day/*[1, 31]*/ = pTm->tm_mday/*[1, 31]*/;
  37.     int hour = pTm->tm_hour/*[0, 23]*/;
  38.     int min = pTm->tm_min/*[0, 59]*/;
  39.     int sec = pTm->tm_sec/*[0, 59]*/;

  40.     /**/
  41.     if(((int)(mon -= 2)) <= 0)
  42.     {
  43.         mon += 12;/* Puts Feb last since it has leap day */
  44.         year -= 1;
  45.     }

  46.     return ((((unsigned long)(year / 4 - year / 100 + year / 400 + 367 * mon / 12 + day) + year * 365 - 719499) * 24
  47.                     + hour /* now have hours */) * 60 + min /* now have minutes */)*60 + sec; /* finally seconds */
  48. }


  49. int main(int argc, char **argv)
  50. {
  51.     unsigned long time1 = 0;
  52.     unsigned long time2 = 0;
  53.     date_time_t time;

  54.     time.tm_year = 17;
  55.     time.tm_mon = 5;
  56.     time.tm_mday = 16;
  57.     time.tm_hour = 9;
  58.     time.tm_min = 9;
  59.     time.tm_sec = 9;

  60.     /**/
  61.     time1 = Dt_mktime_abs(&time);
  62.     time2 = My_mktime(2017, 5, 16, 9, 9, 9);

  63.     printf("time1:%ld,time2:%ld\n", time1, time2);

  64.     return 0;
  65. }


阅读(2356) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~