strptime()等效于Windows?

An̲*_*rew 38 c c++ windows datetime

是否有strptime()适用于Windows的等效实现?不幸的是,这个POSIX功能似乎不可用.

打开strptime的组描述 - 摘要:它将文本字符串转换"MM-DD-YYYY HH:MM:SS"为a tm struct,与之相反strftime().

amw*_*ter 30

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

  1. 使用解析日期 sscanf
  2. 然后将整数复制到a中struct tm(从月份减去1,从年份减去1900 - 月份为0-11,年份从1900年开始)
  3. 最后,用于mktime获取UTC纪元整数

只需记住将isdst成员设置struct tm为-1,否则您将遇到夏令时问题.

  • 请注意,`mktime`适用于1970~2038范围内的日期,但您可以使用[`_mktime64`](http://msdn.microsoft.com/en-us/library/d1y53h2a%28v=vs.80% 29.aspx)适用于1970~3000范围内的日期:) (6认同)

Ada*_*eld 19

strptime()可在此处找到开源版本(BSD许可证):http://cvsweb.netbsd.org/bsdweb.cgi/src/lib/libc/time/strptime.c?rev=HEAD

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

char *strptime(const char * __restrict, const char * __restrict, struct tm * __restrict);
Run Code Online (Sandbox Code Playgroud)

  • 这是如何被接受的答案。它使用了 Windows 中不包含的一堆标头。 (4认同)

Orv*_*ing 16

假设您使用的是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());
}
Run Code Online (Sandbox Code Playgroud)

请注意,对于跨平台应用程序,std::get_time直到GCC 5.1才实现,因此切换到std::get_time直接调用可能不是一种选择.

  • 感谢您可以复制粘贴。 (2认同)

rav*_*int 13

这样做的工作:

#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 );
Run Code Online (Sandbox Code Playgroud)

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

  • +1用于指出跨平台解决方案. (2认同)