muduo源码解析8-date类

date

class date:copyable
{
};

作用:

此类作用主要是实现年月日和julianDay的互相转换
内部最重要的一个数据成员m_julianDayNumber
在mymuduo::detail中提供了相互转换的两个函数getJulianDayNumber和getYearMonthDay具体如何转换的内容没有深究.
注意构造函数可以用julianday,年月日,struct tm三种类型去初始化,实际上都是年月日和julianDay之间的相互转换.
toIosString 返回 格式化字符串 yyyy-mm-dd
另外提供了一些返回年,月,日,周几的函数

成员变量:

struct YearMonthDay
{
int year; //1900-2500
int month; //1-12
int day; //1-31
};

public:
    static const int kDaysPerWeek=7;        //一周7天
    static const int kJulianDayof1970_01_01;//1970.1.1至今的julianDay
private:
    int m_julianDayNumber; 

 

成员函数:

//一些构造函数,空,用年月日,julianDay,struct tm初始化内部m_julianDayNumber
    date():m_julianDayNumber(0){}
    date(int year,int mon,int day);

    explicit date(int julianDayNum):m_julianDayNumber(julianDayNum){}
    explicit date(const struct tm&);
    //交换两个date类型,实际上交换内部m_julianDayNumber的值
    void swap(date& that)
    {
        std::swap(this->m_julianDayNumber,that.m_julianDayNumber);
    }
    //m_julianDayNumber是否>0
    bool valid()const {return m_julianDayNumber>0;}

    //格式化类型 yyyy-mm-dd
    string toIsoString() const;

    //返回年月日类型
    YearMonthDay yearMonthDay() const;

    //返回:年,月,日,周几
    int year() const{return yearMonthDay().year;}
    int month() const{return yearMonthDay().month;}
    int day() const{return yearMonthDay().day;}

    int weekDay() const
    {
        return (m_julianDayNumber+1)%kDaysPerWeek;
    }

    //获取内部数据成员m_julianDayNumber
    int julianDayNumber()const{return m_julianDayNumber;}

detail命名空间内部重要函数:

namespace mymuduo {

namespace detail{
char require_32_bit_integer_at_least[sizeof(int) >= sizeof(int32_t) ? 1 : -1];
//detail中最重要的两个函数,是实现年月日和m_julianDayNumber转换的最基本函数
//根据年月日获得julian日
int getJulianDayNumber(int year, int month, int day)
{
  (void) require_32_bit_integer_at_least; // no warning please
  int a = (14 - month) / 12;
  int y = year + 4800 - a;
  int m = month + 12 * a - 3;
  return day + (153*m + 2) / 5 + y*365 + y/4 - y/100 + y/400 - 32045;
}

//根据julian日获得年月日
struct date::YearMonthDay getYearMonthDay(int julianDayNumber)
{
  int a = julianDayNumber + 32044;
  int b = (4 * a + 3) / 146097;
  int c = a - ((b * 146097) / 4);
  int d = (4 * c + 3) / 1461;
  int e = c - ((1461 * d) / 4);
  int m = (5 * e + 2) / 153;
  date::YearMonthDay ymd;
  ymd.day = e - ((153 * m + 2) / 5) + 1;
  ymd.month = m + 3 - 12 * (m / 10);
  ymd.year = b * 100 + d - 4800 + (m / 10);
  return ymd;
}
}

const int date::kJulianDayof1970_01_01 = detail::getJulianDayNumber(1970, 1, 1);
}

测试:

#include"base/date.h"
#include<iostream>

namespace mymuduo{
namespace currentthread {
void cacheTid()
{
}
}
}

int main()
{
    struct tm* ttm;
    time_t tt=time(NULL);

    ttm=localtime(&tt);

    mymuduo::date dt1(2020,8,23),dt2(*ttm);
    std::cout<<dt1.julianDayNumber()<<" "<<dt2.julianDayNumber()<<std::endl;
    std::cout<<dt1.toIsoString()<<std::endl;

}

打印结果:

2459085 2459085
2020-08-23

 

posted @ 2020-08-23 13:03  WoodInEast  阅读(178)  评论(0编辑  收藏  举报