6
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?

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
Manhooo
  • 115
  • 2
  • 6

2 Answers2

10

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");
Ilya
  • 4,583
  • 4
  • 26
  • 51
  • 1
    `s/not the system locale/not the default locale/` - default is *initially* the process's locale (e.g. from `TZ` environment variable), but can be changed by `QLocale::setDefault()`. – Toby Speight May 05 '17 at 12:59
4

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).

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
  • Whilst this code snippet is welcome, and may provide some help, it would be greatly improved if it included an explanation of how it addresses the question. Without that, your answer has much less educational value - remember that you are answering the question for readers in the future, not just the person asking now! Please edit your answer to add explanation, and give an indication of what limitations and assumptions apply. – Ed Morton May 08 '17 at 14:14