Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost parse date/time string and yield .NET-compatible Ticks value

I'd like to use C++/Boost to parse time strings such as 1980.12.06 21:12:04.232 and acquire a ticks value that would correspond to the tick count( used to initialize .NET's System.DateTime). How can I do it?

Update: I do need to use C++; I cannot use C++/CLI for this.

like image 532
Dmitri Nesteruk Avatar asked Mar 25 '12 21:03

Dmitri Nesteruk


1 Answers

  • in .Net Date time starts from 01.01.01 00:00:00
  • in boost ptime starts from 1400.01.01 00.00.00

//c++ code

#include <boost/date_time/posix_time/posix_time.hpp>
int main(int argc, char* argv[])
{
    using namespace boost::posix_time;
    using namespace boost::gregorian;

    //C# offset till 1400.01.01 00:00:00
    uint64_t netEpochOffset = 441481536000000000LL;

    ptime ptimeEpoch(date(1400,1,1), time_duration(0,0,0));

    //note: using different format than yours, you'll need to parse the time in a different way
    ptime time = from_iso_string("19801206T211204,232");

    time_duration td = time - netEpoch;
    uint64_t nano = td.total_microseconds() * 10LL;

    std::cout <<"net ticks = " <<nano + netEpochOffset;

    return 0;
}

// outputs 624805819242320000

in c# to test

static void Main(string[] args)
{
    DateTime date = new DateTime(1400,1,1);
    Console.WriteLine(date.Ticks);

    DateTime date2 = new DateTime(624805819242320000L); //C++ output
    Console.WriteLine(date2);

            /*output
             * 441481536000000000
             * 6/12/1980 21:12:04
             * */
    return;
}
like image 55
Marius Avatar answered Nov 05 '22 18:11

Marius