Implement formatted output.

This commit is contained in:
John Ralls 2015-04-26 18:01:23 -07:00
parent cbb01c94ae
commit 3f87f56e2e
3 changed files with 27 additions and 1 deletions

View File

@ -102,7 +102,7 @@ public:
operator struct tm() const;
void now() { m_time = boost::local_time::local_sec_clock::local_time(tzp.get(boost::gregorian::day_clock::local_day().year())); }
long offset() const;
std::string format(const char* format) const;
private:
LDT m_time;
};
@ -127,6 +127,18 @@ GncDateTimeImpl::offset() const
return offset.total_seconds();
}
std::string
GncDateTimeImpl::format(const char* format) const
{
using Facet = boost::local_time::local_time_facet;
std::stringstream ss;
//The stream destructor frees the facet, so it must be heap-allocated.
auto output_facet(new Facet(format));
ss.imbue(std::locale(std::locale(), output_facet));
ss << m_time;
return ss.str();
}
/* =================== Presentation-class Implementations ====================*/
GncDate::GncDate() : m_impl{new GncDateImpl} {}
GncDate::GncDate(int year, int month, int day) :
@ -167,3 +179,9 @@ GncDateTime::offset() const
{
return m_impl->offset();
}
std::string
GncDateTime::format(const char* format) const
{
return m_impl->format(format);
}

View File

@ -95,6 +95,7 @@ public:
explicit operator struct tm() const;
long offset() const;
bool isnull (void) { return m_impl == nullptr; }
std::string format(const char* format) const;
private:
std::unique_ptr<GncDateTimeImpl> m_impl;

View File

@ -69,3 +69,10 @@ TEST(gnc_datetime_constructors, test_struct_tm_constructor)
EXPECT_EQ((24 + tm1.tm_hour - atime.offset() / 3600) % 24, tm.tm_hour);
EXPECT_EQ(tm1.tm_min, tm.tm_min);
}
TEST(gnc_datetime_functions, test_format)
{
GncDateTime atime(2394187200); //2045-11-13 12:00:00 Z
//Date only to finesse timezone issues. It will still fail in +12 DST.
EXPECT_EQ(atime.format("%d-%m-%Y"), "13-11-2045");
}