diff options
| author | Carl Hetherington <cth@carlh.net> | 2025-11-13 12:30:31 +0100 |
|---|---|---|
| committer | Carl Hetherington <cth@carlh.net> | 2025-11-13 12:30:38 +0100 |
| commit | a1d0ec67f0ab65b61140d28cfb726812c1604cdc (patch) | |
| tree | b423f3bdc4e7a33e7a5fff6d83de51a6349bdf5b | |
| parent | f5f1ae4c166b99409ca36ab14d53a9bafb001c49 (diff) | |
Add LocalTime::as_time_t().
| -rw-r--r-- | src/local_time.cc | 10 | ||||
| -rw-r--r-- | src/local_time.h | 1 | ||||
| -rw-r--r-- | test/local_time_test.cc | 6 |
3 files changed, 17 insertions, 0 deletions
diff --git a/src/local_time.cc b/src/local_time.cc index f125b38f..d22e07a7 100644 --- a/src/local_time.cc +++ b/src/local_time.cc @@ -418,3 +418,13 @@ LocalTime::as_utc() const return t; } + +time_t +LocalTime::as_time_t() const +{ + DCP_ASSERT(_year >= 1970); + + auto const since_epoch = boost::gregorian::date(_year, _month, _day) - boost::gregorian::date(1970, boost::gregorian::Jan, 1); + return ((((static_cast<time_t>(since_epoch.days()) * 24) + _hour) * 60) + _minute) * 60 + _second; +} + diff --git a/src/local_time.h b/src/local_time.h index c76b876c..a213d0cc 100644 --- a/src/local_time.h +++ b/src/local_time.h @@ -96,6 +96,7 @@ public: * 2013-01-05T18:06:59 or 2013-01-05T18:06:59.123 */ std::string as_string(bool with_millisecond = false, bool with_timezone = true) const; + time_t as_time_t() const; /** @return The date in the form YYYY-MM-DD */ std::string date () const; diff --git a/test/local_time_test.cc b/test/local_time_test.cc index 894f177b..6c7a2472 100644 --- a/test/local_time_test.cc +++ b/test/local_time_test.cc @@ -335,3 +335,9 @@ BOOST_AUTO_TEST_CASE(local_time_comparison_test) BOOST_CHECK(dcp::LocalTime("2014-01-01T10:00:00+02:00") == dcp::LocalTime("2014-01-01T08:00:00")); BOOST_CHECK(dcp::LocalTime("2014-01-01T10:00:00+02:00") == dcp::LocalTime("2014-01-01T11:00:00+03:00")); } + + +BOOST_AUTO_TEST_CASE(local_time_to_time_t) +{ + BOOST_CHECK(dcp::LocalTime("2021-08-04T10:31:55").as_time_t() == 1628073115); +} |
