Convert a String to Date in C++
To convert a std::string to date in C++, we can use the std::stringstream
class along with the std::get_time()
function provided in the <iomanip>
a library that parses the string stream interpreting its content as a date and time specification to fill the tm
structure.
Syntax of get_time()
ss >> get_time(&tm, "%Y-%m-%d");
Here,
ss
is the string stream to be converted to date."%Y-%m-%d"
is the format of the date in the string.tm
is thetm
structure to store the date.
C++ Program to Convert String to Date
The below program demonstrates how we can convert a string to date using std::get_time()
function in C++.
// C++ program to illustrate how to convert string to date
#include <ctime>
#include <iomanip>
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
// Define a string representing a date
string dateString = "2024-03-14";
// Initialize a tm structure to hold the parsed date
tm tm = {};
// Create a string stream to parse the date string
istringstream ss(dateString);
// Parse the date string using std::get_time
ss >> get_time(&tm, "%Y-%m-%d");
// Check if parsing was successful
if (ss.fail()) {
cout << "Date parsing failed!" << endl;
return 1;
}
// Convert the parsed date to a time_t value
time_t date = mktime(&tm);
// Output the parsed date using std::asctime
cout << "Date: " << asctime(localtime(&date));
return 0;
}
Output
Date: Thu Mar 14 00:00:00 2024
Time Complexity: O(N), here N is the length of the date string.
Auxiliary Space: O(1)
How to Convert String to Date in C++?
In C++, we generally store the date and time data in the form of the object of type std::tm. Sometimes, this data is stored inside a string object and we need to convert it into the tm type for further processing. In this article, we will learn how to convert a string to date in C++.
Example:
Input: dateString = "2024-03-14"; Output: Date: Thu Mar 14 00:00:00 2024
Contact Us