Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

String format to 2 digit zero padding numbers



  • I have a question about string format. I need to format a date to a String with zero padding.
    Like 2020.01.27

    I use

    QString strCreationTime = QString("%1.%2.%3 %4:%5:%6").arg(QString::number(pISOVolumeInfo.sInfoEx.ISOCreationDateTime.nDay), 
    QString::number(pISOVolumeInfo.sInfoEx.ISOCreationDateTime.nMonth),
    QString::number(pISOVolumeInfo.sInfoEx.ISOCreationDateTime.nYear+1900),
    QString::number(pISOVolumeInfo.sInfoEx.ISOCreationDateTime.nHour), QString::number(pISOVolumeInfo.sInfoEx.ISOCreationDateTime.nMinute),
    QString::number(pISOVolumeInfo.sInfoEx.ISOCreationDateTime.nSecond));
    

    How is it possible to bring one digit numbers to 2 digit zero padding? Something like sprintf possible with QString?


  • Lifetime Qt Champion

    As @J-Hilk said, there are overloads like this:

    QString number = QString("%1.%2").arg(number, 2, 10, QLatin1Char('0')).arg(number2, 2, 10, QLatin1Char('0');

    But it may be easier if you convert your ISOCreationDateTime into QDateTime and use the string formating from there?

    Regards


  • Moderators

    @pixbyte please read the documentation
    https://doc.qt.io/qt-5/qstring.html

    arg has multiple overloads, more than one allows you to add 0 padding



  • You are right but I so not know how to use with this multiple formating %1%2%3, for one, just like %1 it is easy.


  • Lifetime Qt Champion

    As @J-Hilk said, there are overloads like this:

    QString number = QString("%1.%2").arg(number, 2, 10, QLatin1Char('0')).arg(number2, 2, 10, QLatin1Char('0');

    But it may be easier if you convert your ISOCreationDateTime into QDateTime and use the string formating from there?

    Regards


Log in to reply