Get current Date and Time in Qt
QML[edit | edit source]
The current date/time can be obtained in QML using Javascript’s date:
var today = new Date() // contains current date and time
QML provides the Qt.formatDate() and Qt.formatDateTime() methods for formatting this value. You can also dynamically declare dates using the QML date basic type.
An example displaying the current date in YYMMDD format might look like:
Rectangle {
width: 200
height: 200
Text {
anchors.centerIn: parent
text: Qt.formatDateTime(new Date(), "yyMMdd")
}
}
Qt C++ API[edit | edit source]
The main Qt C++ methods for getting the current date and time are:
- Template:Qapiname returns the current date and time, as reported by the system clock, in the local time zone.
- Template:Qapiname returns the current date, as reported by the system clock, in the local time zone.
- Template:Qapiname returns the current time, as reported by the system clock, in the local time zone.
Headers required[edit | edit source]
- include <QDateTime>
Source[edit | edit source]
SystemTime::SystemTime(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
setWindowTitle("System Time");
ui.statusbar->showMessage("Showing system time");
//get current date
QDate date = QDate::currentDate();
QString dateString = date.toString();
ui.label->setText("Date: " + dateString);
//get current time
QTime time = QTime::currentTime();
QString timeString = time.toString();
ui.label_2->setText("Time: " + timeString);
//get current date and time
QDateTime dateTime = QDateTime::currentDateTime();
QString dateTimeString = dateTime.toString();
ui.label_3->setText("Date and Time: " + dateTimeString);
}
Screenshot[edit | edit source]
The code snippet is expected to show current date and time of device.
Code Example[edit | edit source]
- The Code Example will show current date and time on screen and example is tested on Nokia 5800 XpressMusic.