Merge pull request #622 from mgsergio/time_t-to-w3c-datetime

W3C time functions.
This commit is contained in:
Konstantin Shalnev 2015-11-23 13:30:17 +03:00
commit 4f388ae05f
5 changed files with 87 additions and 0 deletions

View file

@ -31,6 +31,7 @@ SOURCES += \
thread_pool.cpp \
threaded_container.cpp \
timer.cpp \
w3ctime.cpp \
HEADERS += \
SRC_FIRST.hpp \
@ -81,4 +82,5 @@ HEADERS += \
threaded_list.hpp \
threaded_priority_queue.hpp \
timer.hpp \
w3ctime.hpp \
worker_thread.hpp \

View file

@ -39,5 +39,6 @@ SOURCES += \
threads_test.cpp \
timer_test.cpp \
worker_thread_test.cpp \
w3ctime_test.cpp \
HEADERS +=

View file

@ -0,0 +1,19 @@
#include "testing/testing.hpp"
#include "base/w3ctime.hpp"
using namespace base;
UNIT_TEST(ParseTime)
{
TEST(NotATime(ParseTime("")), ());
TEST(NotATime(ParseTime("2015-10-11 23:21")), ());
TEST(!NotATime(ParseTime("2015-10-11T23:21Z")), ());
TEST_EQUAL(ParseTime("2015-10-11T23:21Z"), 1444605660, ());
}
UNIT_TEST(TimeToString)
{
TEST_EQUAL(TimeToString(0), "1970-01-01T00:00Z", ());
TEST_EQUAL(TimeToString(1444605660), "2015-10-11T23:21Z", ());
}

43
base/w3ctime.cpp Normal file
View file

@ -0,0 +1,43 @@
#include "w3ctime.hpp"
#include "std/array.hpp"
// It would be better to use c++ standard means of
// time parsing and unparsing like
// time_get/time_put (<locale>) or get_time/put_time (<iomanip>).
// But at the moment of writing they was not widely supporded
// and/or worked incorrect.
//
// All covertions are made in UTC
namespace
{
char constexpr kW3CTimeFormat[] = "%Y-%m-%dT%H:%MZ";
// Two more digits for year.
size_t constexpr kBufSize = sizeof(kW3CTimeFormat) + 2;
} // namespace
namespace base
{
time_t ParseTime(std::string const & w3ctime) noexcept
{
std::tm tm{};
if (strptime(w3ctime.data(), kW3CTimeFormat, &tm) == nullptr)
return -1;
return timegm(&tm);
}
std::string TimeToString(time_t const timestamp)
{
std::tm tm{};
array<char, kBufSize> buff{};
gmtime_r(&timestamp, &tm);
if (strftime(buff.data(), kBufSize, kW3CTimeFormat, &tm) == 0)
buff[0] = 0;
return buff.data();
}
} // namespace base

22
base/w3ctime.hpp Normal file
View file

@ -0,0 +1,22 @@
#pragma once
#include "std/ctime.hpp"
#include "std/string.hpp"
namespace base
{
inline bool NotATime(time_t const t) noexcept { return t == -1; }
// See http://www.w3.org/TR/NOTE-datetime to learn more
// about the format.
// Parses a string of a format YYYY-MM-DDThh:mmTZD
// (eg 1997-07-16T19:20:30.45+01:00).
// Returns timestamp corresponding to w3ctime or -1 on failure.
time_t ParseTime(std::string const & w3ctime) noexcept;
// Converts timestamp to a string of a fromat YYYY-MM-DDThh:mmTZD
// or empty string if cannot convert.
std::string TimeToString(time_t const timestamp);
} // namespace base