Search code examples
c++qtqt5qdateqlocale

How to display a QDate-month with a different locale than system?


The function QDate::toString(const QString &format) allows to display the month name with MMM (e.g. 'Jan' to 'Dec') or MMMM (e.g. 'January' to 'December').

But this function uses the system locale from QLocale::system() (source code).

What is the easiest way to display a QDate with a month name, for a specific QLocale ?


Solution

  • You must use toString() method of QLocale instead of QDate.

    QDate d =  QDate::currentDate();
    QList<QLocale> locales {QLocale(QLocale::Spanish),
                QLocale(QLocale::English),
                QLocale(QLocale::Dutch),
                QLocale(QLocale::Japanese),
                QLocale(QLocale::French),
                QLocale(QLocale::Chinese)};
    
    QString format = "dd MMMM yyyy";
    
    for(const QLocale locale: locales){
        qDebug()<<locale.toString(d, format);
    
    }
    

    output:

    "16 octubre 2017"
    "16 October 2017"
    "16 oktober 2017"
    "16 10月 2017"
    "16 octobre 2017"
    "16 十月 2017"