Search code examples
qtqmlinvalid-argument

How to convert String to date type using fromLocaleString() function?


I need to convert the time chosen on two tumblers to date QML type. I want the resulting date to be returned via a function alarm_time().

I am using the Date.fromLocaleString(locale, dateTimeString, format) function for conversion. According to the Qt Documentation the locale argument does not have to be specified.

Here is the simplified code:

Frame {

    function format_number(number) {
        return number < 10 && number >= 0 ? "0" + number : number.toString()
    }

    function alarm_time() {
        return Date.fromLocaleString(
            format_number(hours_tumbler.currentIndex) + ":" + format_number(minutes_tumbler.currentIndex), "hh:mm")
    }

    RowLayout {

        Tumbler {
            id: hours_tumbler
            model: 24
        }

        Tumbler {
            id: minutes_tumbler
            model: 60
        }

    }
}

Now, when invoking the function, I get the following error:

Error: Locale: Date.fromLocaleString(): Invalid arguments

The error is self explanatory...

Later I tried specifying the locale argument according to the instructions in Qt Documentation. The code looks like this now:

Frame {

    function format_number(number) {
        return number < 10 && number >= 0 ? "0" + number : number.toString()
    }

    property var locale: Qt.locale() // Here is something new...

    function alarm_time() {
        return Date.fromLocaleString(locale, // ...and here.
            format_number(hours_tumbler.currentIndex) + ":" + format_number(minutes_tumbler.currentIndex), "hh:mm")
    }

    RowLayout {

        Tumbler {
            id: hours_tumbler
            model: 24
        }

        Tumbler {
            id: minutes_tumbler
            model: 60
        }

    }
}

Now the error message is different:

Cannot override FINAL property

Now I'm stuck and I can't really come up with a solution to this problem. Please help!


Solution

  • You're overriding Frame's existing locale property (It comes from Control). Simply come up with a different name for it:

    property var myLocale: Qt.locale()