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?
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");
A QLocale
object can format dates and times, using the QLocale::toString()
methods that accept QDate
or QDateTime
.
#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")));
}
In American English: 5/5/17 is Friday
In 简体中文: 2017/5/5 is 星期五
In suomi: 5.5.2017 is perjantaina
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With