如何在C++中将字符串转换为datetime

sub*_*ubs 5 c++

我有一个基于时间的结果集(来自函数).但是日期时间值是字符串格式(例如"21:5 Jan 23,11").我想将"21:5 Jan 23,11"转换为datetime.我怎么能用C++做到这一点?我只想过滤今天的记录.所以我需要从"21月1日23日,11日"检索当前日期.

编辑:

我可以使用SYSTEMTIME st获取当前日期和时间; GetSystemTime(ST);

有没有办法转换上述格式的"21:5 Jan 23,11"?

Ars*_*.M. 8

#include <ctime>
#include <iomanip>
#include <iostream>
#include <sstream>

// Converts UTC time string to a time_t value.
std::time_t getEpochTime(const std::wstring& dateTime)
{
   // Let's consider we are getting all the input in
   // this format: '2014-07-25T20:17:22Z' (T denotes
   // start of Time part, Z denotes UTC zone).
   // A better approach would be to pass in the format as well.
   static const std::wstring dateTimeFormat{ L"%Y-%m-%dT%H:%M:%SZ" };

   // Create a stream which we will use to parse the string,
   // which we provide to constructor of stream to fill the buffer.
   std::wistringstream ss{ dateTime };

   // Create a tm object to store the parsed date and time.
   std::tm dt;

   // Now we read from buffer using get_time manipulator
   // and formatting the input appropriately.
   ss >> std::get_time(&dt, dateTimeFormat.c_str());

   // Convert the tm structure to time_t value and return.
   return std::mktime(&dt);
}
Run Code Online (Sandbox Code Playgroud)


小智 3

我不是 C++ 程序员,但在 C 中你可以使用strptime http://pubs.opengroup.org/onlinepubs/009695399/functions/strptime.html