0

I'm learning qml and trying to build a basic clock. Now I'm trying to add zeros before the hours, minutes and seconds when they are less than 10. How to do that most effective way?

Here is the code I'm using:

Item {
    id: time

    width: parent.width
    height: 80

    property date now: new Date()

    property int hours: time.now.getHours()
    property int minutes: time.now.getMinutes()
    property int seconds: time.now.getSeconds()

    property int day: time.now.getDate()

    property var month: ["January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"];

    property int month_number: time.now.getMonth() + 1

    property int year: time.now.getFullYear()

    Text {
        text: time.hours + ":" + time.minutes  + ":" + time.seconds
        font.pixelSize: 48
        font.weight: Font.DemiBold
        color: "#AEB3C3"
    }


    Text {
        text: time.day + " " + time.month[time.month_number] + " " + time.year + " г."
        font.pixelSize: 20
        color: "#AEB3C3"
        y: 60
    }

    Timer {
        id: updateclock
        interval: 1000
        running: true
        repeat: true
        onTriggered: {
            time.now = new Date()
        }
    }
}
burnsi
  • 6,194
  • 13
  • 17
  • 27
olevin
  • 1
  • 2
  • 1
    https://stackoverflow.com/questions/2998784/how-to-output-numbers-with-leading-zeros-in-javascript – folibis Jan 15 '23 at 11:07

1 Answers1

0

Firstly, Javascript had String.prototype.padStart() which can be used to ensure your hh:mm:ss pads your numbers to two digits, e.g.

let hours = 5;
let minutes = 31;
let seconds = 4;

console.log( hours.toString().padStart(2, '0')
     + ':' + minutes.toString().padStart(2, '0')
     + ':' + seconds.toString().padStart(2, '0') );

// Output: 05:31:04

However, in your specific example, technically you should go straight for Qt.formatDateTime which has built in support to display time in both hh:mm:ss and dd MMMM yyyy formats. This has built-in padding zero and language locale options for displaying the month string. Also, it is generally better to use pointSize instead of pixelSize so that your code can work on high DPI devices without the need of applying a DPI scale factor:

import QtQuick
import QtQuick.Controls
Page {
    property double now: Date.now()
    property date nowDate: new Date(now)
    Column {
        anchors.centerIn: parent
        Text {
            text: Qt.formatDateTime(nowDate, "hh:mm:ss")
            color: "#AEB3C3"
            font.pointSize: 20
        }
        Text {
            text: Qt.formatDateTime(nowDate, "dd MMMM yyyy")
            color: "#AEB3C3"
            font.pointSize: 20
        }
    }
    Timer {
        interval: 1000
        repeat: true
        running: true
        onTriggered: now = Date.now()
    }
}

You can Try it Online!

Stephen Quan
  • 21,481
  • 4
  • 88
  • 75