2008-11-26 35 views

回答

14

这做工作:

#include "stdafx.h" 
#include "boost/date_time/posix_time/posix_time.hpp" 
using namespace boost::posix_time; 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    std::string ts("2002-01-20 23:59:59.000"); 
    ptime t(time_from_string(ts)); 
    tm pt_tm = to_tm(t); 

但请注意,该输入字符串为YYYY-MM-DD

+2

+1指出一个跨平台的解决方案。 – stinky472 2010-06-29 03:24:04

28

如果你不想端口的任何代码或谴责你的项目,以提高,你可以这样做:

  1. 解析使用sscanf
  2. 然后复制整数日期为struct tm(从减去1从今年月和1900 - 月是0-11和年1900年开始)
  3. 最后,使用mktime获得UTC划时代整数

只记得设置isdst部件O. f struct tm为-1,否则你将有夏时制问题。

+3

请注意,`mktime`的作用范围约为1970〜2038,但您可以使用[`_mktime64`](http://msdn.microsoft.com/zh-cn/library/d1y53h2a%28v=vs.80 %29.aspx)与日期范围1970〜3000一起工作:) – LihO 2012-12-07 17:15:10

+1

有时它可以使用当前值填充`isdst`,你可以通过`localtime(&current_time) - > tm_isdst;`获得它,其中`current_time ``是'time_t`格式的当前时间,由`time(&current_time)`返回。 – user 2014-10-19 08:46:10

-3

一种替代方法是使用GetSystemTime并将时间信息发送到根据您的格式使用vsnprintf_s解析它的函数。在下面的示例 中,有一个函数会创建一个精度为毫秒的时间字符串 。然后它发送的字符串,根据所期望的格式格式化它的函数:

#include <string> 
#include <cstdio> 
#include <cstdarg> 
#include <atlstr.h> 

std::string FormatToISO8601 (const std::string FmtS, ...) { 
    CStringA BufferString; 
    try { 
     va_list VaList; 
     va_start (VaList, FmtS); 
     BufferString.FormatV (FmtS.c_str(), VaList); 
    } catch (...) {} 
    return std::string (BufferString); 
} 

void CreateISO8601String() { 
    SYSTEMTIME st; 
    GetSystemTime(&st); 
    std::string MyISO8601String = FormatToISO8601 ("%4u-%02u-%02uT%02u:%02u:%02u.%03u", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds); 
} 
+0

你有东西倒退。问题是要求一种将**字符串表示形式**转换为`struct tm`的方式,而您提出了[strftime](https://msdn.microsoft.com/en-us /library/fe06s4ak.aspx)。 – IInspectable 2015-06-16 14:36:59

11

假设你使用Visual Studio 2015或以上,则可以使用此作为一个下拉更换为strptime:

#include <time.h> 
#include <iomanip> 
#include <sstream> 

extern "C" char* strptime(const char* s, 
          const char* f, 
          struct tm* tm) { 
    // Isn't the C++ standard lib nice? std::get_time is defined such that its 
    // format parameters are the exact same as strptime. Of course, we have to 
    // create a string stream first, and imbue it with the current C locale, and 
    // we also have to make sure we return the right things if it fails, or 
    // if it succeeds, but this is still far simpler an implementation than any 
    // of the versions in any of the C standard libraries. 
    std::istringstream input(s); 
    input.imbue(std::locale(setlocale(LC_ALL, nullptr))); 
    input >> std::get_time(tm, f); 
    if (input.fail()) { 
    return nullptr; 
    } 
    return (char*)(s + input.tellg()); 
} 

要知道,跨平台的应用程序,std::get_time没有落实到GCC 5.1,所以切换到通话std::get_time直接可能不是一个选项。