An̲*_*rew 38 c c++ windows datetime
是否有strptime()
适用于Windows的等效实现?不幸的是,这个POSIX功能似乎不可用.
打开strptime的组描述 - 摘要:它将文本字符串转换"MM-DD-YYYY HH:MM:SS"
为a tm struct
,与之相反strftime()
.
amw*_*ter 30
如果您不想移植任何代码或谴责您的项目提升,您可以这样做:
sscanf
struct tm
(从月份减去1,从年份减去1900 - 月份为0-11,年份从1900年开始)mktime
获取UTC纪元整数只需记住将isdst
成员设置struct tm
为-1,否则您将遇到夏令时问题.
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)
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
直接调用可能不是一种选择.
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