2011-01-24 4 views
3

У меня есть набор результатов (из функции), основанный на времени. Но значение datetime находится в строчном формате (например, «21: 5 23 января, 11»). Я хочу конвертировать «21: 5 23 января, 11» в datetime. Как я могу сделать это на C++? Я просто хочу фильтровать записи на сегодня. Поэтому мне нужно получить текущую дату с «21: 5 23 января, 11».Как преобразовать строку в datetime в C++

Edit:

я могу получить текущую дату и время, используя SYSTEMTIME ул; GetSystemTime (& st);

Есть ли способ конвертировать «21: 5 янв. 23, 11» в вышеуказанном формате?

ответ

0

Если все, что вам нужно, чтобы проверить, есть ли у две строки же дата или нет, и если это гарантирует, что строки в том же формате , то нет необходимости преобразовывать его в дату. Вам просто нужно сравнить подстроки после первого символа пробела. Если они одинаковые, то даты совпадают. Вот пример кода:

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; 
} 
+1

хорошее предложение (и более высокую производительность, чем преобразование все строки в дату/время), но следует также добавить, что ему нужно преобразовать 'текущий date' в строку в том же формате, для того, чтобы сравнить – davka

+0

Спасибо Аше для ответа. Но мне нужно сравнить «21: 5 23 января, 11» с текущей датой. Я думаю, что текущее время-дата всегда будет в миллисекундах. Как мне сравнить? – sid

+0

@ Субрат: см. Обновленный код, чтобы получить текущую дату. – Asha

1

Наиболее общий C++ способ заключается в использовании Boost.DateTime.

+1

Хотя это простой способ сделать это, он действительно не дает никакого реального понимания процесса, и всегда возможно, что у него может не быть доступа к этому. – Tango

6
#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); 
} 
Смежные вопросы