2008-11-26 31 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直接可能不是一個選項。