strptime()相当于Windows?

是否有可用于Windows的strptime()等效实现? 不幸的是,这个POSIX函数似乎不可用。

打开strptime的组描述 – 摘要:它将文本string(如"MM-DD-YYYY HH:MM:SS"转换为tm struct ,与strftime()相反。

strptime()的开源版本(BSD许可证strptime()可以在这里find: http : strptime()

您需要添加以下声明才能使用它:

 char *strptime(const char * __restrict, const char * __restrict, struct tm * __restrict); 

如果你不想移植任何代码或谴责你的项目提升,你可以这样做:

  1. 使用sscanfparsingdate
  2. 然后将这些整数复制到一个struct tm (从月份减去1,从年 – 月份减去1900 – 1900年)
  3. 最后,使用mktime获取UTC时期整数

只要记得把struct tmisdst成员设置为-1,否则你将会有夏时制的问题。

这样做的工作:

 #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 ); 

但是请注意,inputstring是YYYY-MM-DD

假设您使用的是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可能不是一个选项。

一种替代方法是使用GetSystemTime并将时间信息发送到一个函数,根据您的格式使用vsnprintf_sparsing它。 在下面的例子中,有一个函数创build一个毫秒精度的时间string。 然后将string发送到一个函数,根据所需的格式对其进行格式化:

 #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); }