我想使用 C++/Boost 来解析时间字符串,例如 1980.12.06 21:12:04.232
并获取一个 ticks
值,该值对应于滴答计数(用于初始化 .NET 的 System.DateTime
)。我该怎么做?
更新:我确实需要使用 C++;我不能为此使用 C++/CLI。
最佳答案
- 在 .Net 中日期时间从 01.01.01 00:00:00 开始
- 在 boost ptime 从 1400.01.01 00.00.00 开始
//C++代码
#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;
}
//输出 624805819242320000
在c#中测试
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;
}
关于c++ - Boost 解析日期/时间字符串并产生 .NET 兼容的 Ticks 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9864339/