PDA

View Full Version : Changing language for QDate



kaszewczyk
24th January 2012, 08:31
Hello,
I have a question about toString(QString format) method of QDate class.
I want to get short name of current month, so I entered format toString("MMM"), everything is ok, but this method returned me short month name in my language and I want it to be short month name in English, is it possible to change language of QDate ?

Best Regards
kaszewczyk

stampede
24th January 2012, 09:36
This is how QDate is creating the short month name:


QString QDate::shortMonthName(int month, QDate::MonthNameType type)
{
if (month < 1 || month > 12) {
month = 1;
}
switch (type) {
case QDate::DateFormat:
return QLocale::system().monthName(month, QLocale::ShortFormat);
case QDate::StandaloneFormat:
return QLocale::system().standaloneMonthName(month, QLocale::ShortFormat);
default:
break;
}
return QString();
}

It's using system locale. From the documentation of QLocale :: system:


On Windows and Mac, this locale will use the decimal/grouping characters and date/time formats specified in the system configuration panel.

So I think easiest way will be to write your own class for translatable QDate with custom toString(), and use QLocale::monthName method, something like:


#include <QApplication>
#include <QDebug>
#include <QDate>

class MyDate
{
public:
MyDate(const QDate& d, const QLocale& loc = QLocale()) : _date(d), _loc(loc)
{}
void setLocale(const QLocale& loc){
this->_loc = loc;
}
void setDate(const QDate& d){
this->_date = d;
}
QDate date() const{
return this->_date;
}
QString toString() const{
return QString("%1 %2 %3").arg(_date.day())
.arg( _loc.monthName(_date.month(), QLocale::ShortFormat) )
.arg(_date.year());
}
protected:
QDate _date;
QLocale _loc;
};

int main(int argc, char **argv) {
MyDate date( QDate::currentDate(), QLocale::English );

qDebug() << date.toString();

return 0;
}

Maybe there is easier way, but I'm not aware of it now.

pataliz0r
6th September 2012, 12:31
More then half an year has passed since this thread was last answered. But anyways here's how I did it, if its helps someone else



QDate date = QDateTime::currentDateTime().date();
QLocale locale = QLocale(QLocale::Swedish, QLocale::Sweden); // set the locale you want here
QString swedishDate = locale.toString(date, "dddd, d MMMM yyyy");


cheers