normalize date formats the C++ way.

This commit is contained in:
John Ralls
2018-05-28 08:56:01 -07:00
parent 174752e28c
commit 74cbde2d4f
2 changed files with 36 additions and 58 deletions

View File

@@ -293,30 +293,6 @@ tz_from_string(std::string str)
return TZ_Ptr(new PTZ(tzstr));
}
/* The 'O', 'E', and '-' format modifiers are not supported by
* boost's output facets. Remove them.
*/
static char *
normalize_format (const char *format)
{
int counter = 0, n_counter = 0;
char *normalized;
normalized = strdup(format);
while (format[counter] != '\0')
{
normalized[n_counter] = format[counter];
if ((format[counter] == '%') && \
(format[counter+1] == '-' || format[counter+1] == 'E' || format[counter+1] == 'O'))
counter++; // skip format modifier
counter++;
n_counter++;
}
normalized[n_counter] = '\0';
return normalized;
}
GncDateTimeImpl::GncDateTimeImpl(std::string str) :
m_time(unix_epoch, utc_zone)
{
@@ -394,16 +370,32 @@ GncDateTimeImpl::date() const
return std::unique_ptr<GncDateImpl>(new GncDateImpl(m_time.local_time().date()));
}
/* The 'O', 'E', and '-' format modifiers are not supported by
* boost's output facets. Remove them.
*/
static inline std::string
normalize_format (const std::string& format)
{
bool is_pct = false;
std::string normalized;
std::remove_copy_if(
format.begin(), format.end(), back_inserter(normalized),
[&is_pct](char e){
bool r = (is_pct && (e == 'E' || e == 'O' || e == '-'));
is_pct = e == '%';
return r;
});
return normalized;
}
std::string
GncDateTimeImpl::format(const char* format) const
{
using Facet = boost::local_time::local_time_facet;
std::stringstream ss;
char *normalized_format = normalize_format(format);
//The stream destructor frees the facet, so it must be heap-allocated.
auto output_facet(new Facet(normalized_format));
auto output_facet(new Facet(normalize_format(format).c_str()));
ss.imbue(std::locale(std::locale(), output_facet));
free(normalized_format);
ss << m_time;
return ss.str();
}
@@ -413,11 +405,9 @@ GncDateTimeImpl::format_zulu(const char* format) const
{
using Facet = boost::posix_time::time_facet;
std::stringstream ss;
char *normalized_format = normalize_format(format);
//The stream destructor frees the facet, so it must be heap-allocated.
auto output_facet(new Facet(normalized_format));
auto output_facet(new Facet(normalize_format(format).c_str()));
ss.imbue(std::locale(std::locale(), output_facet));
free(normalized_format);
ss << m_time.utc_time();
return ss.str();
}
@@ -474,11 +464,9 @@ GncDateImpl::format(const char* format) const
{
using Facet = boost::gregorian::date_facet;
std::stringstream ss;
char *normalized_format = normalize_format(format);
//The stream destructor frees the facet, so it must be heap-allocated.
auto output_facet(new Facet(normalized_format));
auto output_facet(new Facet(normalize_format(format).c_str()));
ss.imbue(std::locale(std::locale(), output_facet));
free(normalized_format);
ss << m_greg;
return ss.str();
}