QT6 源(83)篇二:日期类型 QDate 的源代码,及功能测试:日期与字符串互相转换时候的格式指定,
(5)
(6)
(7)日期转换为字符串时候的格式指定 :
++
++ 以及字符串转换为日期时候的格式书写 :
(8) 给出源代码,这是 头文件qdatetime . h 里的一部分 :
/*
The QDate class provides date functions.A QDate object represents a particular day, regardless of calendar,
locale or other settings used when creating it or supplied by the system.
It can report the year, month and day of the month that represent the
day with respect to the proleptic Gregorian calendar or any calendar supplied as a
QCalendar object.
QDate objects should be passed by value rather than by reference to const;
they simply package qint64.
QDate 对象表示特定的一天,无论创建它时使用的日历、区域设置或其他设置如何,或者系统提供的设置如何。
它可以报告表示该天的年份、月份和日期,该天相对于推测的格里高利历或作为 OCalendar对象提供的任何日历。
QDate 对象应该通过值而不是通过引用传递给 const;它们只是封装了 qint64。A QDate object is typically created by giving the year, month,
and day numbers explicitly.
Note that QDate interprets year numbers less than 100 as presented,
i.e., as years 1 through 99, without adding any offset. 即解释为公元 0001 年到 0099年
通常,通过明确给出年份、月份和日期数字来创建 QDate 对象。
请注意,QDate 将小于 100 的年份数字解释为所呈现的年份,即1到99年,不添加任何偏移。
静态函数currentDate()创建一个包含从系统时钟读取的日期的 QDate 对象。
使用setDate()也可以显式设置日期。
fromString()函数返回一个QDate给定一个字符串和一个日期格式,该格式用于解释字符串中的日期。The year(), month(), and day() functions provide access to the year, month,
and day numbers. When more than one of these values is needed,
it is more efficient to call QCalendar::partsFromDate(),
to save repeating (potentially expensive) calendrical calculations.即函数原型 QDate QCalendar::dateFromParts(int year, int month, int day) const;Also, dayOfWeek() and dayOfYear() functions are provided.
The same information is provided in textual format by toString().
QLocale can map the day numbers to names, QCalendar can map month numbers to names.QDate provides a full set of operators to compare two QDate objects
where smaller means earlier, and larger means later. 比较运算符的支持You can increment (or decrement) a date by a given number of days using addDays().
Similarly you can use addMonths() and addYears().
The daysTo() function returns the number of days between two dates.The daysInMonth() and daysInYear() functions return how many days there are in
this date's month and year, respectively.
The isLeapYear() function indicates whether a date is in a leap year.
QCalendar can also supply this information, in some cases more conveniently.Note: All conversion to and from string formats is done using the C locale.
For localized conversions, see QLocale.In the Gregorian calendar, there is no year 0.
Dates in that year are considered invalid.
The year -1 is the year "1 before Christ" or "1 before common era."。
The day before 1 January 1 CE, QDate(1, 1, 1),
is 31 December 1 BCE, QDate(-1, 12, 31).
Various other calendars behave similarly; see QCalendar::hasYearZero().
在格里高利历法中,没有公元0年。该年的日期被认为是无效的。公元-1年是“公元前1年”或“公历前1年”。
公元1年1月1日的前一天,QDate(1,1,1),是公元前31年12月31日,QDate(-1,12,31)。
其他各种历法的行为类似;参见QCalendar::hasYearZero()。日期在内部存储为儒略日数,即连续范围内的每一天的整数计数,
公元前4714年11月24日在格里高利历中是儒略日0(公元前4713年1月1日在儒略历中是儒略日0)。
除了是一种高效准确的存储绝对日期的方法外,它还适用于将日期转换为其他日历系统,
如希伯来语、伊斯兰或中文日历。
可以使用QDate::toJulianDay()获取儒略日数,并使用QDate::fromJulianDay()设置儒略日数。
由于技术原因,QDate可以表示的儒略日数范围被限制在-784350574879和784354017364之间,
这意味着从公元前20亿到公元后20亿。这比ODateTime可以表示的日期范围宽七倍以上。*/class Q_CORE_EXPORT QDate
{
private:// using extra parentheses around min to avoid expanding it if it is a macro//在 min 周围使用额外的括号,以避免在它是宏时展开它。static constexpr inline qint64 nullJd() //这仨函数均无注释{ return (std::numeric_limits<qint64>::min)(); }static constexpr inline qint64 minJd () //julian日历的初始值、最大值与最小值{ return Q_INT64_C(-784350574879); }static constexpr inline qint64 maxJd (){ return Q_INT64_C( 784354017364); }qint64 jd; //本类型的最重要的数据成员,就是这一个数字,其代表了日期概念friend class QDateTime; //友元类friend class QDateTimePrivate;friend constexpr //定义的友元函数,比较运算符,以支持对 QTate日期类型的比较操作bool operator==(QDate lhs, QDate rhs) { return lhs.jd == rhs.jd; }friend constexprbool operator!=(QDate lhs, QDate rhs) { return lhs.jd != rhs.jd; }friend constexprbool operator< (QDate lhs, QDate rhs) { return lhs.jd < rhs.jd; }friend constexprbool operator<=(QDate lhs, QDate rhs) { return lhs.jd <= rhs.jd; }friend constexprbool operator> (QDate lhs, QDate rhs) { return lhs.jd > rhs.jd; }friend constexprbool operator>=(QDate lhs, QDate rhs) { return lhs.jd >= rhs.jd; }#ifndef QT_NO_DATASTREAM //说明数据流支持对日期类型 QDate的 插入>> 与输出<< 操作friend Q_CORE_EXPORT QDataStream & operator<<(QDataStream &, QDate );friend Q_CORE_EXPORT QDataStream & operator>>(QDataStream &, QDate &);
#endifexplicit constexpr QDate(qint64 julianDay) : jd(julianDay) {} //私有构造函数public://Constructs a null date. Null dates are invalid.constexpr QDate() : jd(nullJd()) {}//Returns the current date, as reported by the system clock.static QDate currentDate();//Constructs a date with year y, month m and day d.//The date is understood in terms of the Gregorian calendar.//If the specified date is invalid, the date is not set and isValid()//returns false.//Warning: Years 1 to 99 are interpreted as is. Year 0 is invalid.QDate(int y, int m, int d); //若 y=50,就表示公元 0050年QDate(int y, int m, int d, QCalendar cal); //先不考虑别的日历//Returns true if this date is valid; otherwise returns false.constexpr bool isValid() const { return jd >= minJd() && jd <= maxJd(); }//Returns true if the date is null; otherwise returns false.//A null date is invalid.constexpr bool isNull () const { return !isValid(); }static bool isValid(int y, int m, int d);//Returns true if the specified date (year, month, and day) is valid in the//Gregorian calendar; otherwise returns false.static bool isLeapYear(int year);//Returns true if the specified year is a leap year in the Gregorian calendar;//otherwise returns false.// Gregorian-optimized: 格里高利日历其实就是公历int year () const; //Returns the year of this date.int month () const; //Returns the month-number for the date.//返回值是 1 到 12,对应一月到 12 月。Returns 0 if the date is invalid.int day () const; //Returns the day of the month for this date.//return ranges from 1 to 31. Returns 0 if the date is invalid.int dayOfWeek () const; //Returns 0 if the date is invalid. 对应的星期值//Returns the weekday (1 = Monday to 7 = Sunday) for this date.//(1--7)int dayOfYear () const; //Returns 0 if the date is invalid. 本天在本年里的序号值//Returns the day of the year (1 for the first day) for this date.//(1--365)int daysInMonth() const; //the result ranges from 28 to 31 所在月的月天数//Returns the number of days in the month for this date. //(28--31)int daysInYear () const; // (365--366)所在年的年天数//the result is 365 or 366. Returns 0 if the date is invalid.//Returns the number of days in the year for this date.//返回ISO 8601周数(1到53)。 如果日期无效,则返回0。否则,返回该日期的星期数。//如果 yearNumber不是 nullptr(其默认值),则将年份存储为 *yearNumber。//根据ISO 8601,一年中大部分天数所属的周,在格里高利历中属于该周。//由于IS08601的周从周一开始,因此这是该周周四所在的年份。大多数年份有52周,但有些年份有53周。//注:*yearNumber并不总是与year()相同。 //返回本天所在星期的在年里的星期序号//例如,2000年1月1日是1999年的第52周,而2002年12月31日是2003年的第1周。//取值范围(1--53)int weekNumber (int * yearNum = nullptr) const; // ISO 8601, always Gregorianqint64 daysTo(QDate d) const; //Returns 0 if either date is invalid.//Returns the number of days from this date to d//(which is negative if d is earlier than this date).int year (QCalendar cal) const;int month (QCalendar cal) const;int day (QCalendar cal) const;int dayOfWeek (QCalendar cal) const;int dayOfYear (QCalendar cal) const;int daysInMonth(QCalendar cal) const;int daysInYear (QCalendar cal) const;QDateTime startOfDay(const QTimeZone & zone) const;//enum Qt::TimeSpec { LocalTime, UTC, OffsetFromUTC, TimeZone };QDateTime startOfDay(Qt::TimeSpec spec = Qt::LocalTime,int offsetSeconds = 0) const;//Returns the start-moment of the day. Usually,//this shall be midnight at the start of the day。//The offsetSeconds is ignored unless spec is Qt::OffsetFromUTC,//when it gives the implied zone's offset from UTC.//As UTC and such zones have no transitions,//the start of the day is QTime(0, 0) in these cases.//输出样式举例:QDateTime(2025-05-07 00:00:00.000 中国标准时间 Qt::LocalTime)//输出样式举例:QDateTime(2025-05-07 23:59:59.999 中国标准时间 Qt::LocalTime)QDateTime endOfDay(Qt::TimeSpec spec = Qt::LocalTime,int offsetSeconds = 0) const;//Returns the end-moment of the day. Usually,//this is one millisecond before the midnight at the end of the day。//The offsetSeconds is ignored unless spec is Qt::OffsetFromUTC。QDateTime endOfDay(const QTimeZone & zone) const;//Extracts the date's year, month, and day,//and assigns them to * year, * month, and * day. The pointers may be null.void getDate(int * year, int * month, int * day) const;bool setDate(int year, int month, int day); // Gregorian-optimized//Sets this to represent the date, in the Gregorian calendar,//with the given year, month and day numbers.//Returns true if the resulting date is valid,//otherwise it sets this to represent an invalid date and returns false.bool setDate(int year, int month, int day, QCalendar cal);//Returns a QDate object containing a date days later than the//date of this object (or earlier if ndays is negative).//Returns a null date if the current date is invalid or//the new date is out of range. //经测试,这五个 add*** 函数并不改变自身对象的值。[[nodiscard]] QDate addDays (qint64 days) const; // Gregorian-optimized://Returns a QDate object containing a date months later than the//date of this object (or earlier if nmonths is negative).//Uses cal as calendar, if supplied, else the Gregorian calendar.//Note: If the ending day/month combination does not exist in the//resulting month/year, this function will return a date that is the//latest valid date in the selected month.[[nodiscard]] QDate addMonths(int months ) const;[[nodiscard]] QDate addMonths(int months, QCalendar cal) const;[[nodiscard]] QDate addYears (int years ) const;[[nodiscard]] QDate addYears (int years , QCalendar cal) const;//Returns a QDate object containing a date years later than the//date of this object (or earlier if nyears is negative).//Uses cal as calendar, if supplied, else the Gregorian calendar.//Note: If the ending day/month combination does not exist in the//resulting year (e.g., for the Gregorian calendar,//if the date was Feb 29 and the final year is not a leap year),//this function will return a date that is the latest valid date in the//given month (in the example, Feb 28).//该枚举类下的输出依次是 "Wed May 7 2025"、"2025-05-07"、"07 May 2025"、"2025-05-07"//enum Qt::DateFormat { TextDate, ISODate, RFC2822Date = 8, ISODateWithMs };QString toString(Qt::DateFormat format = Qt::TextDate) const;QString toString(QStringView format, QCalendar cal = QCalendar()) const;//Returns the date as a string. The format parameter determines the format of//the result string. If cal is supplied, it determines the calendar used to//represent the date; it defaults to Gregorian. //按自定义格式转换日期为字符串//任何被单引号括起来的字符序列都会被原样地包含在输出字符串中(去掉引号)即使它包含格式化字符。//在输出中,连续的两个单引号""会被一个单引号替换。 // yyyy MM dd 类似这样的格式字符串//格式字符串中的所有其他字符都会被原样地包含在输出中。//没有分隔符的格式(例如“ddMM”)是支持的,但必须谨慎使用,因为生成的字符串并不总是可读的//(例如,如果“dM”产生“212”,它可能意味着12月2日或2月21日)//If the datetime is invalid, an empty string will be returned.//Note: Day and month names are given in English (C locale).//If localized month and day names are desired, use QLocale::system().toString().QString toString(const QString & format, QCalendar cal = QCalendar()) const{ return toString(qToStringViewIgnoringNull(format), cal); }//代码举例:QDate(2025, 9, 6).toString("年 yyyy, 月 MM, 日 dd 或 d, 星期 dddd")"//代码举例:qDebug() << QDate::fromString("++2003--6**23", "++yyyy--M**dd");//Returns the QDate represented by the string, using the format given,//or an invalid date if the string cannot be parsed. //格式符依然是 y M d 这些//所有其他输入字符将被视为文本。//任何被单引号括起来的非空字符序列也会被(去掉引号)视为文本,而不是被解释为表达式。//For any field that is not represented in the format 将采用以下的默认值://对于格式中未表示的任何字段,使用以下默认值: 1990 1月 1日static QDate fromString(const QString & string,const QString & format, //自定义格式QCalendar cal = QCalendar()){ return fromString(string, qToStringViewIgnoringNull(format), cal); }static QDate fromString(const QString & string, //这个版本用公用格式Qt::DateFormat format = Qt::TextDate){ return fromString(qToStringViewIgnoringNull(string), format); }//Returns the QDate represented by the string, using the format given,//or an invalid date if the string cannot be parsed.//Note for Qt::TextDate: only English month names//(e.g. "Jan" in short form or "January" in long form) are recognized.static QDate fromString(const QString & string,QStringView format,QCalendar cal = QCalendar());static QDate fromString(QStringView string,Qt::DateFormat format = Qt::TextDate);static QDate fromString(QStringView string, QStringView format,QCalendar cal = QCalendar()) //引入了日历参数{ return fromString(string.toString(), format, cal); }#if QT_CONFIG(datestring) //经验证,此 #if 成立
//******************************略# if QT_STRINGVIEW_LEVEL < 2
//***************
# endif//******************************略
#endif //完结 #if QT_CONFIG(datestring)//儒略日是一种以连续日数计算时间的计时法,由法国学者Joseph Justus Scaliger于1583年创立,//旨在统一不同历法的日期系统。//其起点设定为公元前4713年1月1日中午12时(儒略历),对应格里历的公元前4714年11月24日。//这一天是三种周期(28年太阳周期、19年太阴周期、15年罗马征税周期)的共同起点,//形成了7980年的“儒略周期”。 //这也是 JulianDay 的由来static constexpr inline QDate fromJulianDay(qint64 jd_){ return jd_ >= minJd() && jd_ <= maxJd() ? QDate(jd_) : QDate() ; }constexpr inline qint64 toJulianDay() const { return jd; }
}; //完结 class QDate
Q_DECLARE_TYPEINFO(QDate, Q_RELOCATABLE_TYPE); //关于内存管理的宏定义
//关于此宏的定义见源文章 13
(9)
谢谢