Convert String to Date

Convert String to Date in C++ (4 Programs)

IntermediateTopic: Application Programs
Back

C++ Convert String to Date Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
#include <string>
#include <sstream>
#include <ctime>
using namespace std;

struct Date {
    int day;
    int month;
    int year;
};

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

int main() {
    string dateString = "25/12/2024";
    
    // Method 1: Using stringstream
    Date date1 = parseDateString(dateString);
    
    cout << "Date string: " << dateString << endl;
    cout << "Parsed date - Day: " << date1.day 
         << ", Month: " << date1.month 
         << ", Year: " << date1.year << endl;
    
    // Method 2: Using sscanf
    int day, month, year;
    sscanf(dateString.c_str(), "%d/%d/%d", &day, &month, &year);
    cout << "\nUsing sscanf - Day: " << day 
         << ", Month: " << month 
         << ", Year: " << year << endl;
    
    return 0;
}
Output
Date string: 25/12/2024
Parsed date - Day: 25, Month: 12, Year: 2024

Using sscanf - Day: 25, Month: 12, Year: 2024

Understanding Convert String to Date

This program demonstrates 4 different methods to convert a string to date: using stringstream with getline(), using sscanf(), using regex, and using manual parsing. Date formats can vary (DD/MM/YYYY, MM-DD-YYYY, etc.).

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Table of Contents