Convert String to Date in C++
Convert String to Date in C++ (4 Programs).
1#include <iostream>2#include <string>3#include <sstream>4#include <ctime>5using namespace std;67struct Date {8 int day;9 int month;10 int year;11};1213Date parseDateString(string dateStr) {14 Date date;15 stringstream ss(dateStr);16 string token;1718 // Parse day19 getline(ss, token, '/');20 date.day = stoi(token);2122 // Parse month23 getline(ss, token, '/');24 date.month = stoi(token);2526 // Parse year27 getline(ss, token, '/');28 date.year = stoi(token);2930 return date;31}3233int main() {34 string dateString = "25/12/2024";3536 // Method 1: Using stringstream37 Date date1 = parseDateString(dateString);3839 cout << "Date string: " << dateString << endl;40 cout << "Parsed date - Day: " << date1.day41 << ", Month: " << date1.month42 << ", Year: " << date1.year << endl;4344 // Method 2: Using sscanf45 int day, month, year;46 sscanf(dateString.c_str(), "%d/%d/%d", &day, &month, &year);47 cout << "\nUsing sscanf - Day: " << day48 << ", Month: " << month49 << ", Year: " << year << endl;5051 return 0;52}
Output
Date string: 25/12/2024 Parsed date - Day: 25, Month: 12, Year: 2024 Using sscanf - Day: 25, Month: 12, Year: 2024
What's going on
The program converts a date string (e.g., "25/12/2024") into separate day, month, and year components. For example:
The program demonstrates multiple parsing methods, each with different advantages and use cases.
Header Files Used
Understanding Date String Parsing
Date Formats
:
Parsing Challenge
:
Date Structure
struct Date {
int day;
int month;
int year;
};
How it works
:
Method 1: Using stringstream with getline()
Date parseDateString(string dateStr) {
Date date;
stringstream ss(dateStr);
string token;
getline(ss, token, '/');
date.day = stoi(token);
// Parse month
getline(ss, token, '/');
date.month = stoi(token);
// Parse year
getline(ss, token, '/');
date.year = stoi(token);
return date;
}
1// Parse day
How it works
:
Step-by-step
(for "25/12/2024"):
Method 2: Using sscanf()
int day, month, year;
sscanf(dateString.c_str(), "%d/%d/%d", &day, &month, &year);
How it works
:
Advantages
:
Disadvantages
:
Understanding getline() with Delimiter
getline() Function
:
Example
:
Other Methods (Mentioned but not shown in code)
Method 3: Using Regex
regex pattern(R"((\d+)/(\d+)/(\d+))");
smatch matches;
if (regex_match(dateString, matches, pattern)) {
day = stoi(matches[1]);
month = stoi(matches[2]);
year = stoi(matches[3]);
}
1#include <regex>
Method 4: Manual Parsing
When to Use Each Method
-
stringstream + getline()
: Best for learning - clear and flexible, recommended.
-
sscanf()
: Good for simple, fixed formats - efficient one-liner.
-
Regex
: Best for complex formats - powerful pattern matching.
-
Manual Parsing
: Good for custom requirements - maximum control.
Best Practice
: Use stringstream for most cases - it's clear, flexible, and modern C++.
Important Considerations
Date Format Assumptions
:
Input Validation
:
Error Handling
: