一、有效日期范围
日期在内部存储为儒略日数,即连续范围内每一天的整数计数,公历中公元前 4714 年 11 月 24 日为儒略日 0(儒略历中公元前 4713 年 1 月 1 日)。它不仅是一种存储绝对日期的有效且准确的方式,还适用于将日期转换为其他日历系统,例如希伯来语、伊斯兰或中文。
由于技术原因,QDate 可以表示的儒略日数字范围限制在 -784350574879 和 784354017364 之间,这意味着从公元前 20 亿年前到公元 20 亿年后。这是 QDateTime 可以表示的日期范围的七倍多。
二、成员函数
1、QString toString(const QString &format, QCalendar cal = QCalendar())
以字符串形式返回日期。format 参数确定结果字符串的格式。如果提供了 cal,则它确定用于表示日期的日历,默认为公历。
- d:作为没有前导零的数字的日期(1 到 31)
- dd:作为带前导零的数字的日期(01 到 31)
- ddd:缩写的日期名称('Mon' 到 'Sun')
- dddd:长日名称('Monday' 到 'Sunday')
- M:没有前导零的数字形式的月份(1 到 12)
- MM:月份为带前导零的数字(01 到 12)
- MMM:缩写的月份名称(“Jan”到“Dec”)
- MMMM:长月份名称(“一月”到“十二月”)
- yy:两位数的年份(00 到 99)
- yyyy:四位数的年份。
2、QDate addDays(qint64 ndays)
返回的 QDate 对象包含比此对象的日期晚 n 天的日期(如果 ndays 为负,则早n天)。
3、QDate addMonths(int nmonths, QCalendar cal)
返回的QDate 对象包含比此对象的日期晚 n 个月的日期(如果 nmonths 为负,则早n月)。
4、QDate addYears(int nyears, QCalendar cal) / QDate addYears(int nyears)
返回的QDate 对象包含比此对象的日期晚 n 年的日期(如果 nyears 为负,则早n年)。
5、[static] QDate currentDate()
返回系统时钟报告的当前日期。
6、int dayOfWeek(QCalendar cal) / int dayOfWeek()
返回此日期是星期几(1 = 星期一到 7 = 星期日)。
7、int dayOfYear(QCalendar cal) / int dayOfYear()
返回此日期是一年中的第几天。
8、int daysInMonth(QCalendar cal) / int daysInMonth()
返回此日期所属月份中的天数。
9、int daysInYear(QCalendar cal) / int daysInYear()
返回此日期所属的年份的天数。
10、qint64 daysTo(QDate d)
返回从当前日期到 d 的天数(如果 d 早于当前日期,则返回负数)。
QDate d1(2021, 5, 17);
QDate d2(2021, 5, 20);
d1.daysTo(d2); // returns 3
d2.daysTo(d1); // returns -3
11、[static] QDate fromJulianDay(qint64 jd) / qint64 toJulianDay()
儒略日与QDate相互转换。
12、[static] QDate fromString(const QString &string, const QString &format, QCalendar cal = QCalendar())
使用给定的格式返回由字符串表示的 QDate,如果无法解析字符串,则返回无效日期。
qDebug()<< QDate::fromString("1.30", "M.d");
qDebug()<< QDate::fromString("20000110", "yyyyMMdd");
qDebug()<< QDate::fromString("20000110", "yyyyMd");
qDebug()<< QDate::fromString("2021-09-21","yyyy-MM-dd");
qDebug()<< QDate::fromString("2021测09试21","yyyy测MM试dd");
13、void getDate(int *year, int *month, int *day)
提取日期的年、月和日,并将它们分配给 *year、*month 和 *day。
14、[static] bool isLeapYear(int year)
如果指定年份是否公历中的闰年。
15、bool isNull()
此函数的行为等效于 isValid()。
16、bool isValid() / [static] bool isValid(int year, int month, int day)
是否有效 / 指定的日期(年、月和日)在公历中是否有效。
17、int month(QCalendar cal)
返回日历对象 ca 的月数。
18、QString toString(Qt::DateFormat format = Qt::TextDate)
以字符串形式返回日期。format 参数确定字符串的格式。
qDebug()<< QDate::currentDate().toString(Qt::TextDate);
qDebug()<< QDate::currentDate().toString(Qt::ISODate);
qDebug()<< QDate::currentDate().toString(Qt::RFC2822Date);
qDebug()<< QDate::currentDate().toString(Qt::ISODateWithMs);
qDebug()<< QLocale::system().toString(QDate::currentDate());
19、int weekNumber(int *yearNumber = nullptr)
返回 ISO 8601 周数(1 到 53)。(当前日期是一年第几周)
如果 yearNumber 不是 nullptr 则将年份存储为 *yearNumber。
注意:*yearNumber 并不总是与 year() 相同。例如,2000 年 1 月 1 日在 1999 年的第 52 周,2002 年 12 月 31 日在 2003 年的第 1 周。