代码之家  ›  专栏  ›  技术社区  ›  The Unknown

C++将日期时间字符串转换为划时代

  •  9
  • The Unknown  · 技术社区  · 15 年前

    是否有一个C/C++/STL /Boost清理方法将日期时间字符串转换成历元时间(秒)?

    yyyy:mm:dd hh:mm:ss
    
    3 回复  |  直到 15 年前
        1
  •  10
  •   Community CDub    7 年前

    见: Date/time conversion: string representation to time_t

    还有: [Boost-users] [date_time] So how come there isn't a to_time_t helper func?

    所以,很明显像这样的事情应该奏效:

    #include <boost/date_time/posix_time/posix_time.hpp>
    using namespace boost::posix_time;
    
    std::string ts("2002-01-20 23:59:59");
    ptime t(time_from_string(ts));
    ptime start(gregorian::date(1970,1,1)); 
    time_duration dur = t - start; 
    time_t epoch = dur.total_seconds();    
    

    但我不认为它比 Rob's suggestion 使用 sscanf 将数据解析为 struct tm 然后打电话 mktime .

        2
  •  3
  •   Rageous    15 年前

    在Windows平台上,如果不想使用Boost,可以这样做:

    // parsing string
    SYSTEMTIME stime = { 0 };
    sscanf(timeString, "%04d:%02d:%02d %02d:%02d:%02d",
           &stime.wYear, &stime.wMonth,  &stime.wDay,
           &stime.wHour, &stime.wMinute, &stime.wSecond);
    
    // converting to utc file time
    FILETIME lftime, ftime;
    SystemTimeToFileTime(&stime, &lftime);
    LocalFileTimeToFileTime(&lftime, &ftime);
    
    // calculating seconds elapsed since 01/01/1601
    // you can write similiar code to get time elapsed from other date
    ULONGLONG elapsed = *(ULONGLONG*)&ftime / 10000000ull;
    

    如果您喜欢标准库,可以使用struct tm和mktime()来完成相同的工作。