Customise locale default date format to ensure we eliminate issues parsing two-digit year strings

Signed-off-by: Claudio Cambra <claudio.cambra@nextcloud.com>
This commit is contained in:
Claudio Cambra 2023-08-08 17:27:11 +08:00 коммит произвёл Matthieu Gallien
Родитель d2900bad11
Коммит 7ad97cf9e8
2 изменённых файлов: 21 добавлений и 4 удалений

Просмотреть файл

@ -15,12 +15,28 @@
#include "datefieldbackend.h"
#include <QLocale>
#include <QRegularExpression>
namespace OCC
{
namespace Quick
{
DateFieldBackend::DateFieldBackend(QObject *const parent)
: QObject(parent)
{
// Ensure the date format is for a full year. QLocale::ShortFormat often
// provides a short year format that is only two years, which is an absolute
// pain to work with -- ensure instead we have the full, unambiguous year
_dateFormat = QLocale::system().dateFormat(QLocale::ShortFormat);
// Check for specifically two y's, no more and no fewer, within format date
const QRegularExpression re("(?<!y)y{2}(?!y)");
if (auto match = re.match(_dateFormat); match.hasMatch()) {
_dateFormat.replace(match.capturedStart(), match.capturedLength(), "yyyy");
}
}
QDateTime DateFieldBackend::dateTime() const
{
return _dateTime;
@ -53,14 +69,13 @@ void DateFieldBackend::setDateTimeMsecs(const qint64 dateTimeMsecs)
QString DateFieldBackend::dateTimeString() const
{
const auto locale = QLocale::system();
return _dateTime.toString(locale.dateFormat(QLocale::ShortFormat));
return _dateTime.toString(_dateFormat);
}
void DateFieldBackend::setDateTimeString(const QString &dateTimeString)
{
const auto locale = QLocale::system();
const auto dt = locale.toDateTime(dateTimeString, locale.dateFormat(QLocale::ShortFormat));
const auto dt = locale.toDateTime(dateTimeString, _dateFormat);
setDateTime(dt);
}

Просмотреть файл

@ -39,7 +39,7 @@ class DateFieldBackend : public QObject
Q_PROPERTY(bool validDateTime READ validDateTime NOTIFY dateTimeChanged NOTIFY minimumDateTimeChanged NOTIFY maximumDateTimeChanged)
public:
explicit DateFieldBackend() = default;
explicit DateFieldBackend(QObject *const parent = nullptr);
[[nodiscard]] QDateTime dateTime() const;
[[nodiscard]] qint64 dateTimeMsecs() const;
@ -73,6 +73,8 @@ private:
QDateTime _dateTime = QDateTime::currentDateTimeUtc();
QDateTime _minimumDateTime;
QDateTime _maximumDateTime;
QString _dateFormat;
};
} // namespace Quick