码迷,mamicode.com
首页 > 编程语言 > 详细

mktime c语言实现

时间:2016-08-17 23:08:58      阅读:288      评论:0      收藏:0      [点我收藏+]

标签:

 

 

代码:

#include <time.h>

enum TIME_DEF
{
    SEC = 1,
    MIN = SEC * 60,
    HOUR = MIN * 60,
    DAY = HOUR * 24,
    YEAR = DAY * 365,
};

time_t time_difference = 8 * HOUR;
static time_t mon_yday[2][12] =
{
    {0,31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334},
    {0,31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335},
};

int leap(int year) {
    if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0)) {
        return 1;
    }
    return 0;
}
long long get_day(int year) {
    year = year - 1;
    int leap_year_num = year / 4 - year / 100 + year / 400;
    long long tol_day = year * 365 + leap_year_num;
    return tol_day;
}

time_t mymktime(int year,int mon,int day,int hour,int min,int sec) {
    long long tol_day = 0;
    year += 1900;
    tol_day = get_day(year) - get_day(1970);
    tol_day += mon_yday[leap(year)][mon];
    tol_day += day - 1;

    long long ret = 0;
    ret += tol_day * DAY;
    ret += hour * HOUR;
    ret += min * MIN;
    ret += sec * SEC;

    return ret - time_difference;
}

time_t mymktime(tm* mk) {
    if (!mk) {
        return -1;
    }
     if (!(mk->tm_sec>= 0 && mk->tm_sec <= 59)) {
         return -1;
     }
     if (!(mk->tm_min>= 0 && mk->tm_min <= 59)) {
         return -1;
     }
     if (!(mk->tm_hour>= 0 && mk->tm_hour <= 23)) {
         return -1;
     }
     if (!(mk->tm_mday>= 1 && mk->tm_hour <= 31)) {
         return -1;
     }
     if (!(mk->tm_mon>= 0 && mk->tm_mon <= 11)) {
         return -1;
     }
     if (!(mk->tm_year>= 70)) {
         return -1;
     }

     return mymktime(mk->tm_year,mk->tm_mon,mk->tm_mday,mk->tm_hour,mk->tm_min,mk->tm_sec);
}
 

  

mktime c语言实现

标签:

原文地址:http://www.cnblogs.com/ysen/p/5782102.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!