C++ 如何在C++中将字符串转换为日期时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4781852/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:27:55  来源:igfitidea点击:

How to convert a string to datetime in C++

c++

提问by subs

I have a resultset(from a function) which is based on time. But the datetime value is in string format(e.g. "21:5 Jan 23, 11"). I want to convert "21:5 Jan 23, 11" to datetime. How can I do this in C++? I just want to filter records for today. So i need to retrieve the current date from "21:5 Jan 23, 11".

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

Edit:

编辑:

I can get the current date and time using SYSTEMTIME st; GetSystemTime(&st);

我可以使用 SYSTEMTIME st 获取当前日期和时间;获取系统时间(&st);

Is there any way to convert "21:5 Jan 23, 11" in the above format?

有没有办法以上述格式转换“21:5 Jan 23, 11”?

回答by Arsen Y.M.

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

回答by subs

I'm not a C++ programmer but in C you can use strptimehttp://pubs.opengroup.org/onlinepubs/009695399/functions/strptime.html

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

回答by ybungalobill

The most general C++ way is to use Boost.DateTime.

最通用的 C++ 方法是使用Boost.DateTime

回答by Asha

If all you need is to check whether two strings have same date or not and if it is guaranteed that strings are in the same format, then there is no need to convert it to date time. You just have to compare the substrings after the first space character. If they are same, then the dates are same. Here is the sample code:

如果您只需要检查两个字符串是否具有相同的日期,并且可以保证字符串的格式相同,则无需将其转换为日期时间。您只需要比较第一个空格字符之后的子字符串。如果它们相同,则日期相同。这是示例代码:

using namespace std;

string getCurrentDate()
{
    //Enumeration of the months in the year
    const char* months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};

    //Get the current system date time
    SYSTEMTIME st; 
    GetSystemTime(&st);

    //Construct the string in the format "21:5 Jan 23, 11"
    ostringstream ss;
    ss<<st.wHour<<":"<<st.wMinute<<
        " "<<months[st.wMonth-1]<<
        " "<<st.wDay<<", "<<st.wYear%1000;

    //Extract the string from the stream
    return ss.str();

}

string getDateString(const string& s)
{
    //Extract the date part from the string "21:5 Jan 23, 11"

    //Look for the first space character in the string
    string date;
    size_t indx = s.find_first_of(' ');
    if(indx != string::npos) //If found
    {
        //Copy the date part
        date = s.substr(indx + 1);
    }
    return date;
}
bool isCurrentDate(const string& s1)
{
    //Get the date part from the passed string
    string d1 = getDateString(s1);

    //Get the date part from the current date
    string d2 = getDateString(getCurrentDate());

    //Check whether they match
    return ! d1.empty() && ! d2.empty() && d1 == d2;
}

int main( void )
{
    bool s = isCurrentDate("21:5 Jan 23, 11");
    bool s1 = isCurrentDate("21:5 Jan 25, 11");
    return 0;
}