Convert String to Date in C++

Parse a date string like "25/12/2024" into day, month, and year in C++ with getline on '/' and stoi, then with sscanf. Covers validation and malformed input.

IntermediateApplication ProgramsExample 3 of 3
convert-string-to-date.cpp
1#include <iostream>
2#include <string>
3#include <sstream>
4#include <ctime>
5using namespace std;
6
7struct Date {
8 int day;
9 int month;
10 int year;
11};
12
13Date parseDateString(string dateStr) {
14 Date date;
15 stringstream ss(dateStr);
16 string token;
17
18 // Parse day
19 getline(ss, token, '/');
20 date.day = stoi(token);
21
22 // Parse month
23 getline(ss, token, '/');
24 date.month = stoi(token);
25
26 // Parse year
27 getline(ss, token, '/');
28 date.year = stoi(token);
29
30 return date;
31}
32
33int main() {
34 string dateString = "25/12/2024";
35
36 // Method 1: Using stringstream
37 Date date1 = parseDateString(dateString);
38
39 cout << "Date string: " << dateString << endl;
40 cout << "Parsed date - Day: " << date1.day
41 << ", Month: " << date1.month
42 << ", Year: " << date1.year << endl;
43
44 // Method 2: Using sscanf
45 int day, month, year;
46 sscanf(dateString.c_str(), "%d/%d/%d", &day, &month, &year);
47 cout << "\nUsing sscanf - Day: " << day
48 << ", Month: " << month
49 << ", Year: " << year << endl;
50
51 return 0;
52}

Sample Output

Parsed date - Day: 25, Month: 12, Year: 2024

From the stringstream method.

In this one

  • How getline with a delimiter splits a string
  • How stoi turns each piece into an int
  • How a struct groups related values
  • How sscanf parses a pattern in one call

How it works

  1. 1

    dateString holds "25/12/2024".

  2. 2

    parseDateString uses getline(ss, token, '/') three times.

  3. 3

    stoi converts "25", "12", "2024".

  4. 4

    The Date struct is returned and printed.

  5. 5

    sscanf reads the same pattern into three ints.

Edge cases

Wrong separator

Use "25-12-2024".

The first getline reads the whole string and stoi parses 25 then stops at "-". The next getline finds nothing and stoi("") throws invalid_argument.

Impossible date

Use "31/02/2024".

Parsing succeeds because nothing checks the calendar. Validate month 1–12 and the day against the month, including leap years.

What's going on

The program converts a date string (e.g., "25/12/2024") into separate day, month, and year components. For example:

Input string: "25/12/2024"
Output: Day = 25, Month = 12, Year = 2024

The code shows multiple parsing methods, each with different advantages and use cases.

Header Files Used

1.#include <iostream>
Provides cout and cin for input/output operations.
2.#include <string>
Provides string class for string manipulation.
Essential for working with date strings.
3.#include <sstream>
Provides stringstream for parsing strings.
Useful for extracting components from delimited strings.
4.#include <ctime>
Provides time-related functions (optional, for advanced date operations).

Understanding Date String Parsing

Date Formats:

DD/MM/YYYY: "25/12/2024" (day/month/year)
MM-DD-YYYY: "12-25-2024" (month-day-year)
YYYY/MM/DD: "2024/12/25" (year/month/day)
Various delimiters: /, -, space

Parsing Challenge:

Extract day, month, year from string
Handle different formats
Validate extracted values
Convert strings to integers

Date Structure

struct Date {

int day;

int month;

int year;

};

How it works:

struct groups related data together
day, month, year store the parsed components
Provides organized way to represent dates

Method 1: Using stringstream with getline()

Date parseDateString(string dateStr) {

Date date;

stringstream ss(dateStr);

string token;

// Parse day

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;

}

How it works:

stringstream converts string to stream
getline(ss, token, '/') extracts text until '/' delimiter
stoi() converts string to integer
Repeated calls extract day, month, year sequentially

Step-by-step (for "25/12/2024"):

getline extracts "25" → date.day = 25
getline extracts "12" → date.month = 12
getline extracts "2024" → date.year = 2024

Method 2: Using sscanf()

int day, month, year;

sscanf(dateString.c_str(), "%d/%d/%d", &day, &month, &year);

How it works:

sscanf() is a C-style function for parsing formatted strings
"%d/%d/%d" is format specifier matching "number/number/number"
c_str() converts C++ string to C-style string
Extracts directly into integer variables

Advantages:

One-line parsing
Efficient for simple formats
Familiar to C programmers

Disadvantages:

Less flexible than stringstream
Requires exact format match
C-style function (not modern C++)

Understanding getline() with Delimiter

getline() Function:

Syntax: getline(stream, string, delimiter)
Extracts characters until delimiter is found
Delimiter is not included in extracted string
Moves stream position after delimiter

Example:

String: "25/12/2024"
getline(ss, token, '/') → token = "25", stream position after first '/'
getline(ss, token, '/') → token = "12", stream position after second '/'
getline(ss, token, '/') → token = "2024", end of string

Other Methods (Mentioned but not shown in code)

Method 3: Using Regex

#include <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]);

}

Uses regular expressions for pattern matching
More flexible for various formats
Can validate format while parsing

Method 4: Manual Parsing

Find delimiter positions manually
Extract substrings using substr()
Convert to integers
More control but more code

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:

Program assumes DD/MM/YYYY format
Different formats require different parsing logic
Consider format validation

Input Validation:

Check if extracted values are valid
Day: 1-31 (varies by month)
Month: 1-12
Year: reasonable range

Error Handling:

Invalid format strings
Missing delimiters
Non-numeric values
Out-of-range values

Common Use Cases

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What does getline(ss, token, '/') read from "25/12/2024" first?

Pick an answer to check it.

Question 2

What does sscanf return on success here?

Pick an answer to check it.

Questions people ask

Which header does sscanf need?

<cstdio>. This listing gets it through other headers on many compilers, but include it yourself to be safe.

Is there a modern date library?

C++20 <chrono> has calendar types like year_month_day.

Why return a struct?

It keeps the three related values together in one return value.