Get current week number
-
@schiessle hi
that is c++ methodQDate date(2019,03,07); int weekNbr = date.weekNumber();
you can do this and make weekNbr reachable from QML using setContextProperty() method:
int main(int argc, char *argv[]) { QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QGuiApplication app(argc, argv); QQmlApplicationEngine engine; QDate date(2019,03,07); int weekNbr = date.weekNumber(); engine.rootContext()->setContextProperty("weekNbr",weekNbr); //use it in QML Component.onCompleted: {console.log("weekNbr : " + weekNbr)}
or full js : (source https://weeknumber.net/how-to/javascript)
Component.onCompleted: { var date = new Date(); date.setHours(0, 0, 0, 0); // Thursday in current week decides the year. date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7); // January 4 is always in week 1. var week1 = new Date(date.getFullYear(), 0, 4); // Adjust to Thursday in week 1 and count number of weeks from date to week1. console.log(1 + Math.round(((date.getTime() - week1.getTime()) / 86400000 - 3 + (week1.getDay() + 6) % 7) / 7)) }
-
@LeLev Thanks for the detailed example and the link to the JavaScript example.
I chosed the JavaScript way and it works nicely!
Background: I use a Qt program which allows to write "plugins" as QML scripts. I want to write such a plugin. Therefore I need a way to get the week number without patching the main program to expose the week number. That's why I choosed the JS way.
-
@LeLev Careful with those js libraries, if you want valid week numbers on the year 2029 or later, maybe choose another library. It just did a quick test (someone please verify)
The first difference I found is on New Year's Eve 2029 (see first picture, screen shot of my Ubuntu 18.04)2nd picture is a dump of weeknumber using that javascript code, ranging from December 28 to January 4 the following year (i.e. 8 days in a row).
3rd picture is a similar dump using QDate.weekNumber();
(Also New Year's Eve 2035 differs)