Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I obtain day name from QDatetime in a different language?

QDateTime date = QDateTime::currentDateTime();
QString week = QDate::shortDayName(date.date().dayOfWeek());

painter.drawText(-30, 20, 65, 40, Qt::AlignHCenter, week);

I'm painting a clock in Qt Creator. My Qt version is 5.8.0. The language of my system is Chinese, so the week is showed in Chinese. Is it about Locale? How can I show the week in English?

like image 707
Manhooo Avatar asked Jan 05 '23 01:01

Manhooo


2 Answers

Yes, if you need to generate a string based on another locale (not the default locale), you need to specify it with a locale object. Try something like this:

QLocale locale(QLocale("en_US"));
QDateTime date = QDateTime::currentDateTime();
QString dateString = locale.toString(date);

If you need only a part of a full date (day of a week or something like this), you can set your format:

QString dateString = locale.toString(date, "dddd, d MMMM yyyy");
like image 147
Ilya Avatar answered Jan 17 '23 02:01

Ilya


A QLocale object can format dates and times, using the QLocale::toString() methods that accept QDate or QDateTime.

Demo:

#include <QDate>
#include <QDebug>
#include <QLocale>

int main()
{
    const QDate date{ 2017, 5, 5 };
    const QLocale locales[]{ QLocale::English, QLocale::Chinese, QLocale::Finnish };

    for (auto const& l: locales)
        qDebug() << qPrintable(QString("In %0: %1 is %2")
            .arg(l.nativeLanguageName(),
                 l.toString(date, QLocale::ShortFormat),
                 l.toString(date, "dddd")));
}

Output

In American English: 5/5/17 is Friday
In 简体中文: 2017/5/5 is 星期五
In suomi: 5.5.2017 is perjantaina


Short answer

You can write

QString week = QLocale{QLocale::English}.toString(date, "dddd");

(although I wouldn't call it week - that makes me expect the week number within the year).

like image 42
Toby Speight Avatar answered Jan 17 '23 02:01

Toby Speight