- GUI
- Windows API tutorial
- Introduction to Windows API
- Windows API main functions
- System functions in Windows API
- Strings in Windows API
- Date & time in Windows API
- A window in Windows API
- First steps in UI
- Windows API menus
- Windows API dialogs
- Windows API controls I
- Windows API controls II
- Windows API controls III
- Advanced controls in Windows API
- Custom controls in Windows API
- The GDI in Windows API
- PyQt4 tutorial
- PyQt5 tutorial
- Qt4 tutorial
- Introduction to Qt4 toolkit
- Qt4 utility classes
- Strings in Qt4
- Date and time in Qt4
- Working with files and directories in Qt4
- First programs in Qt4
- Menus and toolbars in Qt4
- Layout management in Qt4
- Events and signals in Qt4
- Qt4 Widgets
- Qt4 Widgets II
- Painting in Qt4
- Custom widget in Qt4
- The Breakout game in Qt4
- Qt5 tutorial
- Introduction to Qt5 toolkit
- Strings in Qt5
- Date and time in Qt5
- Containers in Qt5
- Working with files and directories in Qt5
- First programs in Qt5
- Menus and toolbars in Qt5
- Layout management in Qt5
- Events and signals in Qt5
- Qt5 Widgets
- Qt5 Widgets II
- Painting in Qt5
- Custom widget in Qt5
- Snake in Qt5
- The Breakout game in Qt5
- PySide tutorial
- Tkinter tutorial
- Tcl/Tk tutorial
- Qt Quick tutorial
- Java Swing tutorial
- JavaFX tutorial
- Java SWT tutorial
- wxWidgets tutorial
- Introduction to wxWidgets
- wxWidgets helper classes
- First programs in wxWidgets
- Menus and toolbars in wxWidgets
- Layout management in wxWidgets
- Events in wxWidgets
- Dialogs in wxWidgets
- wxWidgets widgets
- wxWidgets widgets II
- Drag and Drop in wxWidgets
- Device Contexts in wxWidgets
- Custom widgets in wxWidgets
- The Tetris game in wxWidgets
- wxPython tutorial
- Introduction to wxPython
- First Steps
- Menus and toolbars
- Layout management in wxPython
- Events in wxPython
- wxPython dialogs
- Widgets
- Advanced widgets in wxPython
- Drag and drop in wxPython
- Internationalisation
- Application skeletons in wxPython
- The GDI
- Mapping modes
- Creating custom widgets
- Tips and Tricks
- wxPython Gripts
- The Tetris game in wxPython
- C# Winforms Mono tutorial
- Java Gnome tutorial
- Introduction to Java Gnome
- First steps in Java Gnome
- Layout management in Java Gnome
- Layout management II in Java Gnome
- Menus in Java Gnome
- Toolbars in Java Gnome
- Events in Java Gnome
- Widgets in Java Gnome
- Widgets II in Java Gnome
- Advanced widgets in Java Gnome
- Dialogs in Java Gnome
- Pango in Java Gnome
- Drawing with Cairo in Java Gnome
- Drawing with Cairo II
- Nibbles in Java Gnome
- QtJambi tutorial
- GTK+ tutorial
- Ruby GTK tutorial
- GTK# tutorial
- Visual Basic GTK# tutorial
- PyGTK tutorial
- Introduction to PyGTK
- First steps in PyGTK
- Layout management in PyGTK
- Menus in PyGTK
- Toolbars in PyGTK
- Signals & events in PyGTK
- Widgets in PyGTK
- Widgets II in PyGTK
- Advanced widgets in PyGTK
- Dialogs in PyGTK
- Pango
- Pango II
- Drawing with Cairo in PyGTK
- Drawing with Cairo II
- Snake game in PyGTK
- Custom widget in PyGTK
- PHP GTK tutorial
- C# Qyoto tutorial
- Ruby Qt tutorial
- Visual Basic Qyoto tutorial
- Mono IronPython Winforms tutorial
- Introduction
- First steps in IronPython Mono Winforms
- Layout management
- Menus and toolbars
- Basic Controls in Mono Winforms
- Basic Controls II in Mono Winforms
- Advanced Controls in Mono Winforms
- Dialogs
- Drag & drop in Mono Winforms
- Painting
- Painting II in IronPython Mono Winforms
- Snake in IronPython Mono Winforms
- The Tetris game in IronPython Mono Winforms
- FreeBASIC GTK tutorial
- Jython Swing tutorial
- JRuby Swing tutorial
- Visual Basic Winforms tutorial
- JavaScript GTK tutorial
- Ruby HTTPClient tutorial
- Ruby Faraday tutorial
- Ruby Net::HTTP tutorial
- Java 2D games tutorial
- Java 2D tutorial
- Cairo graphics tutorial
- PyCairo tutorial
- HTML5 canvas tutorial
- Python tutorial
- Python language
- Interactive Python
- Python lexical structure
- Python data types
- Strings in Python
- Python lists
- Python dictionaries
- Python operators
- Keywords in Python
- Functions in Python
- Files in Python
- Object-oriented programming in Python
- Modules
- Packages in Python
- Exceptions in Python
- Iterators and Generators
- Introspection in Python
- Ruby tutorial
- PHP tutorial
- Visual Basic tutorial
- Visual Basic
- Visual Basic lexical structure
- Basics
- Visual Basic data types
- Strings in Visual Basic
- Operators
- Flow control
- Visual Basic arrays
- Procedures & functions in Visual Basic
- Organizing code in Visual Basic
- Object-oriented programming
- Object-oriented programming II in Visual Basic
- Collections in Visual Basic
- Input & output
- Tcl tutorial
- C# tutorial
- Java tutorial
- AWK tutorial
- Jetty tutorial
- Tomcat Derby tutorial
- Jtwig tutorial
- Android tutorial
- Introduction to Android development
- First Android application
- Android Button widgets
- Android Intents
- Layout management in Android
- Android Spinner widget
- SeekBar widget
- Android ProgressBar widget
- Android ListView widget
- Android Pickers
- Android menus
- Dialogs
- Drawing in Android
- Java EE 5 tutorials
- Introduction
- Installing Java
- Installing NetBeans 6
- Java Application Servers
- Resin CGIServlet
- JavaServer Pages, (JSPs)
- Implicit objects in JSPs
- Shopping cart
- JSP & MySQL Database
- Java Servlets
- Sending email in a Servlet
- Creating a captcha in a Servlet
- DataSource & DriverManager
- Java Beans
- Custom JSP tags
- Object relational mapping with iBATIS
- Jsoup tutorial
- MySQL tutorial
- MySQL quick tutorial
- MySQL storage engines
- MySQL data types
- Creating, altering and dropping tables in MySQL
- MySQL expressions
- Inserting, updating, and deleting data in MySQL
- The SELECT statement in MySQL
- MySQL subqueries
- MySQL constraints
- Exporting and importing data in MySQL
- Joining tables in MySQL
- MySQL functions
- Views in MySQL
- Transactions in MySQL
- MySQL stored routines
- MySQL Python tutorial
- MySQL Perl tutorial
- MySQL C API programming tutorial
- MySQL Visual Basic tutorial
- MySQL PHP tutorial
- MySQL Java tutorial
- MySQL Ruby tutorial
- MySQL C# tutorial
- SQLite tutorial
- SQLite C tutorial
- SQLite PHP tutorial
- SQLite Python tutorial
- SQLite Perl tutorial
- SQLite Ruby tutorial
- SQLite C# tutorial
- SQLite Visual Basic tutorial
- PostgreSQL C tutorial
- PostgreSQL Python tutorial
- PostgreSQL Ruby tutorial
- PostgreSQL PHP tutorial
- PostgreSQL Java tutorial
- Apache Derby tutorial
- SQLAlchemy tutorial
- MongoDB PHP tutorial
- MongoDB Java tutorial
- MongoDB JavaScript tutorial
- MongoDB Ruby tutorial
- Spring JdbcTemplate tutorial
- JDBI tutorial
Date and time in Qt4
In this part of the Qt4 C++ programming tutorial, we will talk about time and date.
Qt4 has QDate
, QTime
, and QDateTime
classes to work with date and time. The QDate
is a class for working with a calendar date in the Gregorian calendar. It has methods for determining the date, comparing, or manipulating dates. The QTime
class works with a clock time. It provides methods for comparing time, determining the time and various other time manipulating methods. The QDateTime
is a class that combines both QDate
and QTime
objects into one object.
Initialising date & time objects
Date and time objects can be initialised in two basic ways. We initialise them in the object constructor or we can create empty objects and fill them with data later.
init.cpp
#include <QTextStream> #include <QDate> #include <QTime> int main(void) { QTextStream out(stdout); QDate dt1(2015, 4, 12); out << "The date is " << dt1.toString() << endl; QDate dt2; dt2.setDate(2015, 3, 3); out << "The date is " << dt2.toString() << endl; QTime tm1(17, 30, 12, 55); out << "The time is " << tm1.toString("hh:mm:ss.zzz") << endl; QTime tm2; tm2.setHMS(13, 52, 45, 155); out << "The time is " << tm2.toString("hh:mm:ss.zzz") << endl; }
We initialise date and time object in both ways.
QDate dt1(2015, 4, 12);
The QDate
object constructor takes three parameters: the year, the month, and the day.
out << "The date is " << dt1.toString() << endl;
The date is printed to the console. We use the toString()
method to convert the date object into string.
QTime tm2; tm2.setHMS(13, 52, 45, 155);
An empty QTime
object is created. We fill the object with data using the setHMS()
method. The parameters are the hours, minutes, seconds, and milliseconds.
out << "The time is " << tm2.toString("hh:mm:ss.zzz") << endl;
We print the QTime
object to the console. We use a specific format that includes also the milliseconds, which are omitted by default.
Output
$ ./init The date is Sun Apr 12 2015 The date is Tue Mar 3 2015 The time is 17:30:12.055 The time is 13:52:45.155
Current date & time
In the following example, we print the current local time and date to the console.
curdatetime.cpp
#include <QTextStream> #include <QTime> #include <QDate> int main(void) { QTextStream out(stdout); QDate cd = QDate::currentDate(); QTime ct = QTime::currentTime(); out << "Current date is: " << cd.toString() << endl; out << "Current time is: " << ct.toString() << endl; }
Watch out that the file must not be called time.cpp
.
QDate cd = QDate::currentDate();
The QDate::currentDate()
static function returns the current date.
QTime ct = QTime::currentTime();
The QTime::currentTime()
static function returns the current time.
out << "Current date is: " << cd.toString() << endl; out << "Current time is: " << ct.toString() << endl;
We use the toString()
method to convert the date and time objects to strings.
Output
$ ./curdatetime Current date is: Wed Oct 14 2015 Current time is: 13:40:04
Comparing dates
Relational operators can be used to compare dates. We can compare their position in the calendar.
comparedates.cpp
#include <QTextStream> #include <QDate> int main(void) { QTextStream out(stdout); QDate dt1(2015, 4, 5); QDate dt2(2014, 4, 5); if (dt1 < dt2) { out << dt1.toString() << " comes before " << dt2.toString() << endl; } else { out << dt1.toString() << " comes after " << dt2.toString() << endl; } }
The example compares two dates.
QDate dt1(2015, 4, 5); QDate dt2(2014, 4, 5);
We have two different dates.
if (dt1 < dt2) { out << dt1.toString() << " comes before " << dt2.toString() << endl; } else { out << dt1.toString() << " comes after " << dt2.toString() << endl; }
We compare the dates with a lower than (<) comparison operator and determine which of them is located earlier in the calendar.
Output
$ ./comparedates Sun Apr 5 2015 comes after Sat Apr 5 2014
Comparison operators can be easily used for QTime
and QDateTime
objects too.
Determining a leap year
A leap year is a year containing an additional day. The reason for an extra day in the calendar is the difference between the astronomical and the calendar year. The calendar year has exactly 365 days, while the astronomical year, the time for the earth to make one revolution around the Sun, is 365.25 days. The difference is 6 hours which means that in four years time we are missing one day. Because we want to have our calendar synchronised with the seasons, we add one day to February each four years. (There are exceptions.) In the Gregorian calendar, February in a leap year has 29 days instead of the usual 28. And the year lasts 366 days instead of the usual 365.
The QDate::isLeapYear()
static method determines whether a year is a leap year.
leapyear.cpp
#include <QTextStream> #include <QDate> int main() { QTextStream out(stdout); QList<int> years({2010, 2011, 2012, 2013, 2014, 2015, 2016}); foreach (int year, years) { if (QDate::isLeapYear(year)) { out << year << " is a leap year" << endl; } else { out << year << " is not a leap year" << endl; } } }
In the example we have a list of years. We check each year if it is a leap year.
QList<int> years({2010, 2011, 2012, 2013, 2014, 2015, 2016});
We initialise an list of years. This is C++11 construct, therefore, we need to enable C++11. We need to add the CONFIG += c++11
, QMAKE_CXXFLAGS += -std=c++11
, or QMAKE_CXXFLAGS += -std=c++0x
to the .pro file.
foreach (int year, years) { if (QDate::isLeapYear(year)) { out << year << " is a leap year" << endl; } else { out << year << " is not a leap year" << endl; } }
We go through the list and determine if the given year is a leap year. The QDate::isLeapYear()
returns a boolean true or false.
Output
$ ./leapyear 2010 is not a leap year 2011 is not a leap year 2012 is a leap year 2013 is not a leap year 2014 is not a leap year 2015 is not a leap year 2016 is a leap year
Predefined date formats
Qt4 has some built-in date formats. The toString()
method of a QDate
object takes a date format as a parameter. The default date format used by Qt4 is Qt::TextDate
.
dateformats.cpp
#include <QTextStream> #include <QDate> int main(void) { QTextStream out(stdout); QDate cd = QDate::currentDate(); out << "Today is " << cd.toString(Qt::TextDate) << endl; out << "Today is " << cd.toString(Qt::ISODate) << endl; out << "Today is " << cd.toString(Qt::SystemLocaleShortDate) << endl; out << "Today is " << cd.toString(Qt::SystemLocaleLongDate) << endl; out << "Today is " << cd.toString(Qt::DefaultLocaleShortDate) << endl; out << "Today is " << cd.toString(Qt::DefaultLocaleLongDate) << endl; out << "Today is " << cd.toString(Qt::SystemLocaleDate) << endl; out << "Today is " << cd.toString(Qt::LocaleDate) << endl; }
In the example, we show eight different date formats for the current date.
out << "Today is " << cd.toString(Qt::ISODate) << endl;
Here we print the current date in the Qt::ISODate
format, which is an international standard for displaying dates.
Output
$ ./dateformats Today is Wed Oct 14 2015 Today is 2015-10-14 Today is 10/14/15 Today is Wednesday, October 14, 2015 Today is 10/14/15 Today is Wednesday, October 14, 2015 Today is 10/14/15 Today is 10/14/15
Custom date formats
A date can be represented in a variety of other formats. In Qt4 we can create our custom date formats, too. Another version of the toString()
method takes a format string where we can use various format specifiers. For example the d
specifier stands for a day as a number without a leading zero. The dd
specifier stands for a day as a number with a leading zero. The following table lists available date format expressions:
Expression | Output |
---|---|
d | The day as a number without a leading zero (1 to 31) |
dd | The day as a number with a leading zero (01 to 31) |
ddd | The abbreviated localized day name (e.g. 'Mon' to 'Sun'). Uses QDate::shortDayName(). |
dddd | The long localized day name (e.g. 'Monday' to 'Sunday'). Uses QDate::longDayName(). |
M | The month as a number without a leading zero (1 to 12) |
MM | The month as a number with a leading zero (01 to 12) |
MMM | The abbreviated localized month name (e.g. 'Jan' to 'Dec'). Uses QDate::shortMonthName(). |
MMMM | The long localized month name (e.g. 'January' to 'December'). Uses QDate::longMonthName(). |
yy | The year as two digit number (00 to 99) |
yyyy | The year as four digit number. If the year is negative, a minus sign is prepended in addition. |
Table: Date format specifiers customdateformats.cpp
#include <QTextStream> #include <QDate> int main(void) { QTextStream out(stdout); QDate cd = QDate::currentDate(); out << "Today is " << cd.toString("yyyy-MM-dd") << endl; out << "Today is " << cd.toString("yy/M/dd") << endl; out << "Today is " << cd.toString("d.M.yyyy") << endl; out << "Today is " << cd.toString("d-MMMM-yyyy") << endl; }
We have four custom date formats.
out << "Today is " << cd.toString("yyyy-MM-dd") << endl;
This is the international date format. The parts of the date are separated by a dash character. The yyyy
is a year having four digits. The MM
is the month as a number with a leading zero (01 to 12). And the dd
is the day as a number with a leading zero (01 to 31).
out << "Today is " << cd.toString("yy/M/dd") << endl;
This is another common date format. The parts are separated by a slash (/) character. The M
specifier stands for a month as a number without a leading zero (1 to 12).
out << "Today is " << cd.toString("d.M.yyyy") << endl;
This date format is used in Slovakia. The parts are separated by a dot character. The day and month are without leading zeros. First is the day, then comes the month, and the last is the year.
Output
$ ./customdateformats Today is 2015-10-14 Today is 15/10/14 Today is 14.10.2015 Today is 14-October-2015
Predefined time formats
Time has some predefined formats. The standard format specifiers are identical to those used in the date formats. The default time format used by Qt4 is Qt::TextDate
.
timeformats.cpp
#include <QTextStream> #include <QTime> int main(void) { QTextStream out(stdout); QTime ct = QTime::currentTime(); out << "The time is " << ct.toString(Qt::TextDate) << endl; out << "The time is " << ct.toString(Qt::ISODate) << endl; out << "The time is " << ct.toString(Qt::SystemLocaleShortDate) << endl; out << "The time is " << ct.toString(Qt::SystemLocaleLongDate) << endl; out << "The time is " << ct.toString(Qt::DefaultLocaleShortDate) << endl; out << "The time is " << ct.toString(Qt::DefaultLocaleLongDate) << endl; out << "The time is " << ct.toString(Qt::SystemLocaleDate) << endl; out << "The time is " << ct.toString(Qt::LocaleDate) << endl; }
In the example, we show eight different time formats for the current time.
out << "The time is " << ct.toString(Qt::ISODate) << endl;
Here we print the current time in the Qt::ISODate
format, which is an international standard for displaying times.
Output
$ ./timeformats The time is 16:14:08 The time is 16:14:08 The time is 4:14 PM The time is 4:14:08 PM CEST The time is 4:14 PM The time is 4:14:08 PM CEST The time is 4:14 PM The time is 4:14 PM
Custom time formats
We can create additional time formats. We build a custom time format where we use time format specifiers. The following table gives a list of available format expressions.
Expression | Output |
---|---|
h | the hour without a leading zero (0 to 23 or 1 to 12 if AM/PM display) |
hh | the hour with a leading zero (00 to 23 or 01 to 12 if AM/PM display) |
H | the hour without a leading zero (0 to 23, even with AM/PM display) |
HH | the hour with a leading zero (00 to 23, even with AM/PM display) |
m | the minute without a leading zero (0 to 59) |
mm | the minute with a leading zero (00 to 59) |
s | the second without a leading zero (0 to 59) |
ss | the second with a leading zero (00 to 59) |
z | the milliseconds without leading zeroes (0 to 999) |
zzz | the milliseconds with leading zeroes (000 to 999) |
AP or A | use AM/PM display. AP will be replaced by either "AM" or "PM". |
ap or a | use am/pm display. ap will be replaced by either "am" or "pm". |
t | the timezone (for example "CEST") |
Table: Time format specifiers customtimeformats.cpp
#include <QTextStream> #include <QTime> int main(void) { QTextStream out(stdout); QTime ct = QTime::currentTime(); out << "The time is " << ct.toString("hh:mm:ss.zzz") << endl; out << "The time is " << ct.toString("h:m:s a") << endl; out << "The time is " << ct.toString("H:m:s A") << endl; out << "The time is " << ct.toString("h:m AP") << endl; out << "The version of Qt4 is " << qVersion() << endl; }
We have four custom time formats.
out << "The time is " << ct.toString("hh:mm:ss.zzz") << endl;
In this format, we have hour, minute, and second with a leading zero. We also add the milliseconds with leading zeroes.
out << "The time is " << ct.toString("h:m:s a") << endl;
This time format specifier uses hour, minute, and second without a leading zero and adds am/pm period identifiers.
Output
$ ./customtimeformats The time is 16:15:07.690 The time is 4:15:7 pm The time is 16:15:7 PM t The time is 4:15 PM
Retrieving the weekday
The dayOfWeek()
method returns a number which represents a day of a week, where 1 is Monday and 7 is Sunday.
weekday.cpp
#include <QTextStream> #include <QDate> int main(void) { QTextStream out(stdout); QDate cd = QDate::currentDate(); int wd = cd.dayOfWeek(); out << "Today is " << QDate::shortDayName(wd) << endl; out << "Today is " << QDate::longDayName(wd) << endl; }
In the example we print the short and long names of the current weekday.
QDate cd = QDate::currentDate();
We get the current date.
int wd = cd.dayOfWeek();
From the current date we get the day of week.
out << "Today is " << QDate::shortDayName(wd) << endl;
With the QDate::shortDayName()
static method we get the short name of the weekday.
out << "Today is " << QDate::longDayName(wd) << endl;
Using the QDate::longDayName()
static method we get the long name of the weekday.
Output
$ ./weekday Today is Wed Today is Wednesday
Number of days
We can compute the number of days in a particular month using the daysInMonth()
method and the number of days in a year using the daysInYear()
method.
nofdays.cpp
#include <QTextStream> #include <QDate> int main(void) { QTextStream out(stdout); QList<QString> months; months.append("January"); months.append("February"); months.append("March"); months.append("April"); months.append("May"); months.append("June"); months.append("July"); months.append("August"); months.append("September"); months.append("October"); months.append("November"); months.append("December"); QDate dt1(2015, 9, 18); QDate dt2(2015, 2, 11); QDate dt3(2015, 5, 1); QDate dt4(2015, 12, 11); QDate dt5(2015, 1, 21); out << "There are " << dt1.daysInMonth() << " days in " << months.at(dt1.month()-1) << endl; out << "There are " << dt2.daysInMonth() << " days in " << months.at(dt2.month()-1) << endl; out << "There are " << dt3.daysInMonth() << " days in " << months.at(dt3.month()-1) << endl; out << "There are " << dt4.daysInMonth() << " days in " << months.at(dt4.month()-1) << endl; out << "There are " << dt5.daysInMonth() << " days in " << months.at(dt5.month()-1) << endl; out << "There are " << dt1.daysInYear() << " days in year " << QString::number(dt1.year()) << endl; }
Five date objects are created. We compute the number of days in those months and in a particular year.
QDate dt1(2015, 9, 18); QDate dt2(2015, 2, 11); QDate dt3(2015, 5, 1); QDate dt4(2015, 12, 11); QDate dt5(2015, 1, 21);
Five QDate
objects are created. Each of them represents a different date.
out << "There are " << dt1.daysInMonth() << " days in " << months.at(dt1.month()-1) << endl;
We use the daysInMonth()
method to get the number of days in the date object.
out << "There are " << dt1.daysInYear() << " days in year " << QString::number(dt1.year()) << endl;
And here, we get the number of days in a year using the daysInYear()
method for the date object.
Output
$ ./nofdays There are 30 days in September There are 28 days in February There are 31 days in May There are 31 days in December There are 31 days in January There are 365 days in year 2015
Checking validity of a date
There is a isValid()
method which checks whether a date is valid.
isvalid.cpp
#include <QTextStream> #include <QDate> int main(void) { QTextStream out(stdout); QList<QDate> dates({QDate(2015, 5, 11), QDate(2015, 8, 1), QDate(2015, 2, 30)}); for (int i=0; i < dates.size(); i++) { if (dates.at(i).isValid()) { out << "Date " << i+1 << " is a valid date" << endl; } else { out << "Date " << i+1 << " is not a valid date" << endl; } } }
In the example we check the validity of three days.
QList<QDate> dates({QDate(2015, 5, 11), QDate(2015, 8, 1), QDate(2015, 2, 30)});
The first two days are valid. The third one is invalid. February has 28 or 29 days.
if (dates.at(i).isValid()) { out << "Date " << i+1 << " is a valid date" << endl; } else { out << "Date " << i+1 << " is not a valid date" << endl; }
Depending on the outcome of the isValid()
method, we print a message about a validity of a date to the console.
Output
$ ./isvalid Date 1 is a valid date Date 2 is a valid date Date 3 is not a valid date
Days to, days from
We can easily calculate a date n days from a particular date. We use the addDays()
method. The daysTo()
method returns the number of days to a chosen date.
daystofrom.cpp
#include <QTextStream> #include <QDate> int main(void) { QTextStream out(stdout); QDate dt(2015, 5, 11); QDate nd = dt.addDays(55); QDate xmas(2015, 12, 24); out << "55 days from " << dt.toString() << " is " << nd.toString() << endl; out << "There are " << QDate::currentDate().daysTo(xmas) << " days till Christmas" << endl; }
We get a date 55 day later from May 11, 2015. We also get the number of days till Christmas.
QDate dt(2015, 5, 11); QDate nd = dt.addDays(55);
The addDays()
method returns a QDate
which is 55 days after the given date.
QDate xmas(2015, 12, 24); ... out << "There are " << QDate::currentDate().daysTo(xmas) << " days till Christmas" << endl;
We use the daysTo()
method to calculate the number of days until Christmas.
Output
$ ./daystofrom 55 days from Mon May 11 2015 is Sun Jul 5 2015 There are 71 days till Christmas
QDateTime class
The QDateTime
object contains a calendar date and a clock time. It is a combination of the QDate
and QTime
classes. It has many similar methods and the usage is identical to those two classes.
datetime.cpp
#include <QTextStream> #include <QDateTime> int main(void) { QTextStream out(stdout); QDateTime cdt = QDateTime::currentDateTime(); out << "The current datetime is " << cdt.toString() << endl; out << "The current date is " << cdt.date().toString() << endl; out << "The current time is " << cdt.time().toString() << endl; }
The example retrieves the current datetime.
out << "The current datetime is " << cdt.toString() << endl;
This line of code prints the current datetime to the terminal.
out << "The current date is " << cdt.date().toString() << endl;
This line retrieves the date portion of the datetime object using the date()
method.
Output
$ ./datetime The current datetime is Wed Oct 14 17:02:52 2015 The current date is Wed Oct 14 2015 The current time is 17:02:52
Julian day
A Julian day refers to a continuous count of days since the beginning of the Julian Period. It is used primarily by astronomers. It should not be confused with the Julian calendar. The Julian Period started in 4713 BC. The Julian day number 0 is assigned to the day starting at noon on January 1, 4713 BC. The Julian Day Number (JDN) is the number of days elapsed since the beginning of this period. The Julian Date (JD) of any instant is the Julian day number for the preceding noon plus the fraction of the day since that instant. (Qt4 does not compute this fraction.) Apart from astronomy, Julian dates are often used by military and mainframe programs.
julianday.cpp
#include <QTextStream> #include <QDate> int main(void) { QTextStream out(stdout); QDate cd = QDate::currentDate(); out << "Gregorian date for today: " << cd.toString(Qt::ISODate) << endl; out << "Julian day for today: " << cd.toJulianDay() << endl; }
In the example, we compute the Gregorian date and the Julian day for today.
out << "Julian day for today: " << cd.toJulianDay() << endl;
The Julian day is returned with the toJulianDay()
method.
Output
$ ./julianday Gregorian date for today: 2015-10-14 Julian day for today: 2457310
With Julian date, it is easy to do calculations.
battles.cpp
#include <QTextStream> #include <QDate> int main(void) { QTextStream out(stdout); QDate bordate(1812, 9, 7); QDate slavdate(1805, 12, 2); QDate cd = QDate::currentDate(); int j_today = cd.toJulianDay(); int j_borodino = bordate.toJulianDay(); int j_slavkov = slavdate.toJulianDay(); out << "Days since Slavkov battle: " << j_today - j_slavkov << endl; out << "Days since Borodino battle: " << j_today - j_borodino << endl; }
The example counts the number of days passed since two historical events.
QDate bordate(1812, 9, 7); QDate slavdate(1805, 12, 2);
We have two dates of battles of the Napoleonic era.
int j_today = cd.toJulianDay(); int j_borodino = bordate.toJulianDay(); int j_slavkov = slavdate.toJulianDay();
We compute the Julian days for today and for the Battles of Slavkov and Borodino.
out << "Days since Slavkov battle: " << j_today - j_slavkov << endl; out << "Days since Borodino battle: " << j_today - j_borodino << endl;
We compute the number of days passed since the two battles.
Output
$ date Wed Oct 14 17:35:40 CEST 2015 $ ./battles Days since Slavkov battle: 76652 Days since Borodino battle: 74181
On October 14, 2015, 76652 days have passed since the Battle of Slavkov and 74181 since the battle of Borodino.
UTC time
Our planet is a sphere. It revolves round its axis. The Earth rotates towards the east. So the Sun rises at different times in different locations. The Earth rotates once in about 24 hours. Therefore, the world was divided into 24 time zones. In each time zone, there is a different local time. This local time is often further modified by the daylight saving.
There is a pragmatic need for one global time. One global time helps to avoid confusion about time zones and daylight saving time. The UTC (Universal Coordinated time) was chosen to be the primary time standard. UTC is used in aviation, weather forecasts, flight plans, air traffic control clearances, and maps. Unlike local time, UTC does not change with a change of seasons.
utclocal.cpp
#include <QTextStream> #include <QDateTime> int main(void) { QTextStream out(stdout); QDateTime cdt = QDateTime::currentDateTime(); out << "Universal datetime: " << cdt.toUTC().toString() << endl; out << "Local datetime: " << cdt.toLocalTime().toString() << endl; }
In the example we compute the current datetime. We express the datetime in UTC datetime and local datetime.
out << "Universal datetime" << cdt.toUTC().toString() << endl;
The toUTC()
method is used to get the UTC datetime.
out << "Local datetime" << cdt.toLocalTime().toString() << endl;
The toLocalTime()
is used to get the local datetime.
Output
$ ./localutc Universal datetime: Wed Oct 14 15:50:30 2015 Local datetime: Wed Oct 14 17:50:30 2015
The example was run in Bratislava, which has Central European Summer Time (CEST)—UTC + 2 hours.
The Unix epoch
An epoch is an instant in time chosen as the origin of a particular era. For example in western Christian countries the time epoch starts from day 0, when Jesus was born. Another example is the French Republican Calendar which was used for twelve years. The epoch was the beginning of the Republican Era which was proclaimed on September 22, 1792, the day the First Republic was declared and the monarchy abolished. Computers have their epochs too. One of the most popular is the Unix time. The Unix epoch is the time 00:00:00 UTC on 1 January 1970 (or 1970-01-01T00:00:00Z ISO 8601). The date and time in a computer is determined according to the number of seconds or clock ticks that have elapsed since the defined epoch for that computer or platform.
$ date +%s 1444838231
Unix date command can be used to get the Unix time. At this particular moment, 1444838231 seconds have passed since the Unix epoch.
unixepoch.cpp
#include <QTextStream> #include <QDateTime> #include <ctime> int main(void) { QTextStream out(stdout); time_t t = time(0); out << t << endl; QDateTime dt; dt.setTime_t(t); out << dt.toString() << endl; QDateTime cd = QDateTime::currentDateTime(); out << cd.toTime_t() << endl; }
In the example, we use two Qt4 functions to get the Unix time and convert it to the human readable form.
#include <ctime>
We include the standard C++ time header file.
time_t t = time(0); out << t << endl;
With the standard C++ time()
command, we get the Unix time.
QDateTime dt; dt.setTime_t(t); out << dt.toString() << endl;
The setTime_t()
method is used to convert the Unix time into the DateTime, which is formatted to human readable form.
QDateTime cd = QDateTime::currentDateTime(); out << cd.toTime_t() << endl;
The Qt4's toTime_t()
method can be also used to get the Unix time.
Output
$ ./unixepoch 1444838314 Wed Oct 14 17:58:34 2015 1444838314
In this chapter, we have worked with time and date.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论