kernel/mktime

/*
 *  linux/kernel/mktime.c
 *
 *  Copyright (C) 1991, 1992  Linus Torvalds
 */

#include <linux/mktime.h>

/*
 * This isn't the library routine, it is only used in the kernel.
 * as such, we don't care about years<1970 etc, but assume everything
 * is ok. Similarly, TZ etc is happily ignored. We just do everything
 * as easily as possible. Let's find something public for the library
 * routines (although I think minix times is public).
 */
/*
 * PS. I hate whoever though up the year 1970 - couldn't they have gotten
 * a leap-year instead? I also hate Gregorius, pope or no. I'm grumpy.
 */
#define MINUTE 60                     //1分钟60秒
#define HOUR (60*MINUTE)              //一小时 60 * MINUTE秒
#define DAY (24*HOUR)                 //一天有多少秒
#define YEAR (365*DAY)                //一年有多少秒

/* interestingly, we assume leap-years */
//假设为闰年,计算每个月过去秒数
static int month[12] = {
    0,                                     //进入新的一年过去的秒数
    DAY*(31),                              //一月过去之后占用的秒数
    DAY*(31+29),                           //二月过去之后占用的秒数
    DAY*(31+29+31),                        //三月过去之后占用的秒数
    DAY*(31+29+31+30),                     //四月过去之后占用的秒数
    DAY*(31+29+31+30+31),                  //五月过去之后占用的秒数
    DAY*(31+29+31+30+31+30),               //六月过去之后占用的秒数
    DAY*(31+29+31+30+31+30+31),            //七月过去之后占用的秒数
    DAY*(31+29+31+30+31+30+31+31),         //八月过去之后占用的秒数
    DAY*(31+29+31+30+31+30+31+31+30),      //九月过去之后占用的秒数
    DAY*(31+29+31+30+31+30+31+31+30+31),   //十月过去之后占用的秒数
    DAY*(31+29+31+30+31+30+31+31+30+31+30) //十一月过去之后占用的秒数(12月过去要计算整年)
};
//初始化内核时间
long kernel_mktime(struct mktime * time)
{
    long res;
    int year;

    year = time->year - 70;   //从1970年一月0点0分0秒
/* magic offsets (y+1) needed to get leapyears right.*/
    res = YEAR*year + DAY*((year+1)/4); //从计时时间开始到今年共有多少秒
    res += month[time->mon];            //加上已经过去的月份的秒数(假设为闰年)
/* and (y+2) here. If it wasn't a leap-year, we have to adjust */
    if (time->mon>1 && ((year+2)%4))    //判断是否为闰年,并且是否过了二月,进行时间调整
        res -= DAY;
    res += DAY*(time->day-1);           //加上这个月过去的天数所占有的秒数
    res += HOUR*time->hour;             //加上过去的小时数占有的秒数
    res += MINUTE*time->min;            //加上过去的分钟数占有的秒数
    res += time->sec;                   //加上过去的秒数
    return res;                         //结果为计时开始到现在为止过去的秒数
}

原文地址:https://www.cnblogs.com/xiaofengwei/p/3774005.html