How to transform between a double date-time and std::string in C++

One of the attractions of writing software using the .NET framework is the wealth of support for doing simple things like translating between different data formats. These tasks are typically much harder to achieve in C++ due to the lack of an equivalent framework. One such task that I came across the other day is that date-times are often represented by a double in Windows, where the integer part represents the date since some epoch and the fractional part is the time as a fraction of 24 hours. Even with access to the Boost library, I still had to do some work to produce a simple transformation in C++.

#include <boost/format.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

typedef double DateTime;

namespace
{
  boost::gregorian::date parse_date( DateTime date_time )
  {
      boost::gregorian::date dt = boost::date_time::parse_date<boost::gregorian::date>( "1899-12-30", boost::date_time::ymd_order_iso );
      dt += boost::gregorian::date_duration( static_cast<long>( floor(date_time) ) );
  }

  boost::posix_time::time_duration parse_time( DateTime date_time )
  {
    double fractionalDay = date_time - floor(date_time);
    long milliseconds = static_cast<long>( floor( fractionalDay * 24.0 * 60.0 * 60.0 * 1000.0 + 0.5) );
    return boost::posix_time::milliseconds( milliseconds );
  }
}

std::string to_date_string( DateTime date_time )
{
  boost::gregorian::date dt = parse_date( date_time );
  return (boost::format( "%4-%02d-%02d" ) % dt.year() % dt.month().as_number() % dt.day().as_number()).str();
}

DateTime from_date_string( const std::string& value )
{
  boost::gregorian::date epoch = boost::date_time::parse_date<boost::gregorian::date>( "1899-12-30", boost::date_time::ymd_order_iso);
  boost::gregorian::date dt = boost::date_time::parse_date<boost::gregorian::date>( value, boost::date_time::ymd_order_iso);

  boost::gregorian::date_duration diff = dt - epoch;
  return diff.days();
}

std::string to_date_time_string( DateTime date_time )
{
  boost::gregorian::date date_part = parse_date( date_time );
  boost::posix_time::time_duration time_part = parse_time( date_time );

  long long fractional_seconds = time_part.fractional_seconds();
  boost::date_time::time_resolutions resolution = time_part.resolution();
  if ( resolution == boost::date_time::micro )
  {
    fractional_seconds /= 1000;
  } 
  else
  {
    if (resolution != boost::date_time::milli)
      throw std::logic_error( "Unexpected time resolution" );
  }

  return (boost::format( "%d-%02d-%02d %02d:%02d:%02d.%03d" )
    % date_part.Year() % date_part.month().as_number() % date_part.day().as_number()
    % time_part.hours() % time_part.minutes() % time_part.seconds() % fractional_seconds ).str();
}

DateTime from_date_time_string( const std::string& value )
{
  DateTime date = from_date_string( value );
 
  boost::posix_time::ptime t = boost::posix_time::time_from_string( value );
  double milliseconds = static_cast<double>(t.time_of_day().total_milliseconds());

  return date + (milliseconds / 24.0 / 60.0 / 60.0 / 1000.0);
}

Please comment if you know a more straight-forward way to achieve this transformation, especially using Boost. Syntactically, the code could be simplified using C++11 auto, but I’ve spelt out the types explicitly throughout because I found it helpful to see which parts of the boost library are being used.

1 Comment

Filed under C++, C++ Code, Programming

Book Review – An Astronaut’s Guide to Life On Earth, Chris Hadfield

An Astronaut's Guide to Life on Earth, Chris HadfieldI first saw Chris Hadfield on the excellent Stargazing Live on the BBC and on the strength of that appearance I thought his book would be well worth reading. Despite his many achievements and talents, the book paints him as a humble guy who’s keen to contribute but at pains not to hinder (read his chapter on “Aim to be a Zero” and you’ll get the idea). This book has much to say on the importance of working in a team towards a common goal – I would recommend it alongside How to Win Friends and Influence People for anyone embarking on life in the corporate world.
Four stars

1 Comment

Filed under Book Review

Book Review – Never Go Back, Lee Child

Never Go Back, Lee ChildThis story was long awaited, partly because the author has been building up to the meeting of Jack Reacher with Susan Turner and his journey across America to Virginia for several books – this association started in the book 61 Hours, so definitely worth reading that one and before this. On the other hand, this book is one of the best Jack Reacher thrillers, so you might not want to wait. I was waiting to read this in paperback, but was delighted to receive it in a beautiful hardcover edition for my birthday.

I prefer Jack Reacher novels when he works with an accomplice, often a woman, to solve a case and hand out his own brand of justice to the perpetrators. Never Go Back fits the bill and matches The Enemy for excitement and daring plot as a result. There are other plot twists – this book is all about Reacher’s past coming back to haunt him. Does he have a child? Has one of his many violent episodes resulted in a conviction that will see him jailed? Will his previous service in the army see him forcibly conscripted to serve his country again? I tried hard to pace myself reading this one, having polished off other Reacher novels in a couple of days and then having a long wait for the next one. Unfortunately, once I was a few chapters in, I was hooked and as usual sped through it. The compelling question was – having gone back, would Reacher leave again? Or would he finally have re-discovered a life for which it was worth settling down?

Five Stars

1 Comment

Filed under Book Review

iWatch rumours

I wonder if Apple realise just how much expectations are mounting regarding the launch of an iWatch? When I first heard about it, I loved the idea and the prospect without having a clue what it would do (a bit like the daughter of a colleague who asked for an iPod for Christmas and when he asked what she would use it for replied: “I dunno, I just want one”).

Now, a few months on, my expectations are higher. I want it to look like this:

20140408-183611.jpg

And I want it to monitor my health and fitness, act as a heart rate monitor at the gym so I can exercise optimally, measure my activity during the day like a Nike fuel band, and interface to Google maps so that I can glance at my watch for directions instead of walking along holding out my smart phone.

Maybe all of these expectations will be off the mark – in which case, someone else will benefit from all the marketing that’s going on and Apple will lose out.

Leave a comment

Filed under Musing

Agile and cargo cults

Thought provoking blog post from Mike Hadlow on the way Agile is often hijacked by non-technical managers with little talent.

Somehow, over the decade or so since the original agile manifesto, agile has come to mean ‘management agile’. It’s been captured by management consultants and distilled as a small set of non-technical rituals that emerged from the much larger, richer, but often deeply technical set of agile practices.

I agree with this from one of the many comments:

The most successful teams I have seen made use of “tech leads” who were engineers capable of running a project.

Leave a comment

Filed under Programming

ACCU Meetup: Machine Learning for Fun and Profit

I went to the ACCU London Meet-up on 20th March: Burkhard Kloss on Machine Learning for Fun and Profit.

The core message was that Machine learning is an easy technique to invoke these days, especially with 3rd party libraries on hand like Numpy, Sci-kit Learn. The speaker has used these from Python and demonstrated programs to classify the XOR problem and a data set on Iris flowers dating from Victorian times.

Leave a comment

Filed under Meetup, Programming

Science Jokes

These science jokes popped up on Flipboard today – some really good ones:

@PopSci I was going to tell a joke about sodium, but Na.

— Ian Haygreen (@IanHaygreen) March 24, 2014

@PopSci Being absolute zero is 0K with me

— Бeн (@benmhancock) March 24, 2014

@PopSci heisenberg is pulled over. “Do you have any idea how fast you were going?” asks the policeman. H: “No. But, I know where I am.”

@PopSci Higgs Boson walks into a church and says “you can’t have mass without me!”

Leave a comment

Filed under Musing

Restaurant Review: Baltic, Blackfriars Road, London

Baltic

 

My colleagues and I had a team dinner at Baltic, near Southwark tube station.  The menu has plenty of polish dishes – I had a selection of blinis to start and a roast goose dish to follow.  It was a really good meal and I’d recommend the venue (especially if you are a fan of Vodka – they have over 60 from which to choose!).

Four stars

Leave a comment

Filed under Restaurant Review

Restaurant Review: Cigalon, Chancery Lane, London

Cigalon

Cigalon is a calm, civilised place to dine amongst the hustle and bustle of London. We had a lovely evening there and will definitely go again.
Four starts

Leave a comment

Filed under Restaurant Review

C++ Quiz

This C++ quiz is quite fun – not all of the questions require C++ 11, but some do.

Leave a comment

Filed under C++, Programming