How to add a character to the beginning of a string?



  • Hi,

    I parse json and I want to add "0" character to the beginning of the time string.
    The if(hourLenght === 1){ mHour = "0" + mHour } part is not working in my QML project.

    The whole code:

                if (request.readyState === XMLHttpRequest.DONE) {
                    if (request.status && request.status === 200) {
                        var result = JSON.parse(request.responseText)
                        // BUY
                        textSTG_BUY.text = result.currency.sterling.buy
     
                        // SELL
                        textSTG_SELL.text = result.currency.sterling.sell
    
                        // DATE
                        var temDate = result.tarih
                        var mYear = temDate.slice(0, 4);
                        var mMonth = temDate.slice(4, 6);
                        var mDay = temDate.slice(6, 8);
                        textDATE.text = mDay + "." + mMonth + "." + mYear
    
                        // TIME
                        var d = new Date(); // for now
                        var mHour = d.getHours();
                        var mMinutes = d.getMinutes();
    
                        **var hourLenght = mHour.lenght
                        if(hourLenght === 1){
                            mHour = "0" + mHour
                        }
    
                        var minuteLenght = mMinutes.lenght
                        if(minuteLenght === 1){
                            mMinutes = "0" + mMinutes
                        }**
    
                        textTIME.text = mHour + ":" + mMinutes
                    }
                    else {
                        //console.log("Log:", request.status, request.statusText)
                    }
                }


  • Hi
    Try using formatTime instead of prepending "0" before hours/mins.

                var time = new Date();
                label.text = Qt.formatTime(time,"HH:mm")
    

    -Tirupathi



  • @NTMS
    @Tirupathi-Korla response above is the right way to do what you want.

    However, for the record and for your future, what is wrong with your code is the spelling in mHour.lenght & mMinutes.lenght. The correct spelling is length. (JavaScript being JavaScript, it allows you to mistype this "property" name without warning, and returns undefined as its value.) I suggest you also rename your variables in this light.



  • @Tirupathi-Korla and @JNBarchan I will check it tonight



  • @Tirupathi-Korla Thank you is working. @JNBarchan in my code I spell correctly but didn't work.

    Thank you.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.