subs
subs

Reputation: 2249

How to convert a string to datetime in C++

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".

Edit:

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

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

Upvotes: 10

Views: 42488

Answers (6)

user3818635
user3818635

Reputation: 36

In the function "ValidateAndParseDateTime" above, I think it's supposed to return "bSuccess". Without it, caller will always get "Invalid date and time".

{

Upvotes: 0

Swapnil Kulkarni
Swapnil Kulkarni

Reputation: 41

This is sample program to validate input datetime and parse

#include <iostream>
#include <comutil.h>
#include <iomanip>

bool ValidateAndParseDateTime(const std::wstring & strInputDate, std::tm & date)
{
    bool bSuccess = false;
    if (!strInputDate.empty())
    {
        _variant_t varIn = strInputDate.c_str();
        if (SUCCEEDED(VariantChangeTypeEx(&varIn, &varIn, GetThreadLocale(), 0, VT_DATE)))
        {
            std::get_time(&date, strInputDate.c_str());
            bSuccess = true;
        }
    }
}

int main()
{
    std::tm date;
    std::wstring strInputDate = L"7/20/2020 1:29:37 PM";
    if (!ValidateAndParseDateTime(strInputDate, date))
    {
        //Invalid date and time
    }

    return 0;
}

Upvotes: 2

Arsen Y.M.
Arsen Y.M.

Reputation: 697

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

Upvotes: 12

Asha
Asha

Reputation: 11232

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

Upvotes: 0

Yakov Galka
Yakov Galka

Reputation: 72469

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

Upvotes: 1

user173973
user173973

Reputation:

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

Upvotes: 3

Related Questions