Skip to content

Some examples

Jeremy Dumais edited this page Jun 9, 2024 · 2 revisions

Some examples

Don't forget the namespace

Note: To simplify the example code below, we will assume that you have use the jed_utils namespace in the source file like this:

use namespace jed_utils;

Otherwise if you prefer, you will have to specify the namespace on each class of the library like this :

jed_utils::datetime dtTest = jed_utils::datetime();

Here are some examples

Get the current date and time

datetime dtTest = datetime();

Create a date

datetime dtTest = datetime(2016, 11, 25);

Create a date with time (year, month, day, hour, minute, second)

datetime dtTest = datetime(2016, 11, 25, 20, 12, 44);

Create a date with time (12 hour format) (year, month, day, hour, minute, second, period)

datetime dtTest = datetime(2016, 11, 25, 4, 12, 44, period::PM);

Add a week to a date

datetime dtTest = datetime(2016, 11, 25, 20, 12, 44);
dtTest.add_days(7);

Substract a week from a date

datetime dtTest = datetime(2016, 11, 25, 20, 12, 44);
dtTest.add_days(-7);

Display the date in standard form (yyyy-MM-dd HH:mm:ss)

datetime dtTest = datetime();
cout << dtTest.to_string() << endl;

Display the date in custom format ("yyyy-MM-dd hh:mm:ss tt")

datetime dtTest = datetime();
cout << dtTest.to_string("yyyy-MM-dd hh:mm:ss tt") << endl;

Get weekday of a datetime

//enum weekday { sunday, monday, tuesday, wednesday, thursday, friday, saturday };
datetime dtTest = datetime(2015, 02, 14, 11, 11, 11);
assert(dtTest.get_weekday() == weekday::saturday);

Parse a string to a datetime

datetime dtTest = datetime::parse(string("yyyy/MM/dd HH:mm:ss"), string("2016-08-18 23:14:42"));

Substracting two datetime objetcs (Example 1)

datetime date1(2016, 12, 31, 11, 32, 5);
datetime date2(2016, 12, 25, 13, 55, 12);
timespan ts1 = date2 - date1;
assert(ts1.get_days() == -5);
assert(ts1.get_hours() == -21);
assert(ts1.get_minutes() == -36);
assert(ts1.get_seconds() == -53);

Substracting two datetime objetcs (Example 2)

datetime date1(2016, 11, 25);
datetime date2(2016, 12, 5);
timespan ts1 = date2 - date1;
assert(ts1.get_days() == 10);
assert(ts1.get_hours() == 0);
assert(ts1.get_minutes() == 0);
assert(ts1.get_seconds() == 0);

Get total minutes of a timespan

timespan ts(0, 1, 3, 15);
assert(ts.get_total_minutes() == 63);