Sai A Sai A
Updated date Nov 13, 2023
In this blog, we will learn how to convert date and time strings into usable time objects in C++. This blog presents four different methods, complete with code examples, explanations, and sample outputs.

Introduction:

Working with date and time is a common task in programming, and C++ provides several ways to handle these values. One of the essential operations is converting a string representation of time into a time object that can be used for various purposes. In this blog, we will explore multiple methods to convert a string to a time object in C++.

We will discuss the following methods:

  • Using std::tm and std::istringstream
  • Using std::get_time and std::istringstream
  • Using std::chrono and std::time_point
  • Using third-party libraries like Boost.DateTime

We will provide a program for each method, along with explanations and their respective outputs, so you can choose the method that best suits your needs.

Method 1: Using std::tm and std::istringstream

The first method we will explore involves using the std::tm struct, which represents a calendar date and time, and std::istringstream to parse the input string.

#include <iostream>
#include <sstream>
#include <ctime>

int main() {
    std::string timeStr = "2023-11-06 15:30:00";
    std::tm timeInfo = {};
    std::istringstream timeStream(timeStr);
    timeStream >> std::get_time(&timeInfo, "%Y-%m-%d %H:%M:%S");

    if (timeStream.fail()) {
        std::cerr << "Failed to parse the input string!" << std::endl;
    } else {
        std::time_t time = std::mktime(&timeInfo);
        std::cout << "Method 1 Output: " << std::asctime(&timeInfo);
    }

    return 0;
}
  • We start by defining a string timeStr that contains the date and time in a specific format.
  • We create a std::tm struct named timeInfo, which will hold the parsed date and time.
  • An std::istringstream object, timeStream, is used to parse the string.
  • We use std::get_time to extract the date and time components from the string, specifying the expected format.
  • If the parsing fails, an error message is displayed. Otherwise, we convert timeInfo into a std::time_t object and display it.

Output:

Method 1 Output: Mon Nov  6 15:30:00 2023

Method 2: Using std::get_time and std::istringstream

The second method also employs std::get_time and std::istringstream, but in a slightly different way.

#include <iostream>
#include <sstream>
#include <ctime>

int main() {
    std::string timeStr = "2023-11-06 15:30:00";
    std::tm timeInfo = {};
    std::istringstream timeStream(timeStr);
    timeStream >> std::get_time(&timeInfo, "%Y-%m-%d %H:%M:%S");

    if (timeStream.fail()) {
        std::cerr << "Failed to parse the input string!" << std::endl;
    } else {
        std::cout << "Method 2 Output: ";
        std::cout << std::put_time(&timeInfo, "%c") << std::endl;
    }

    return 0;
}

This method is similar to the previous one, but instead of using std::asctime, we use std::put_time to format and display the time.

Output:

Method 2 Output: Mon Nov  6 15:30:00 2023

Method 3: Using std::chrono and std::time_point

The third method involves using the <chrono> library to represent time points and durations. It's a more modern approach to handling time.

#include <iostream>
#include <chrono>
#include <ctime>
#include <sstream>

int main() {
    std::string timeStr = "2023-11-06 15:30:00";
    std::tm timeInfo = {};
    std::istringstream timeStream(timeStr);
    timeStream >> std::get_time(&timeInfo, "%Y-%m-%d %H:%M:%S");

    if (timeStream.fail()) {
        std::cerr << "Failed to parse the input string!" << std::endl;
    } else {
        std::chrono::system_clock::time_point timePoint = std::chrono::system_clock::from_time_t(std::mktime(&timeInfo));
        std::time_t time = std::chrono::system_clock::to_time_t(timePoint);
        std::cout << "Method 3 Output: " << std::asctime(std::localtime(&time));
    }

    return 0;
}
  • We start by parsing the string as in the previous methods.
  • Instead of using std::tm, we convert it into a std::chrono::system_clock::time_point.
  • We also convert the time point back to a std::time_t object for formatting and display.

Output:

Method 3 Output: Mon Nov  6 15:30:00 2023

Method 4: Using Third-Party Libraries like Boost.DateTime

In some cases, you may need more advanced time parsing and formatting capabilities. In such situations, third-party libraries like Boost.DateTime can be incredibly useful. Here, we'll use Boost.DateTime for time conversion.

Before using Boost.DateTime, make sure you have it installed and properly configured.

#include <iostream>
#include <string>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

int main() {
    std::string timeStr = "2023-11-06 15:30:00";
    boost::posix_time::ptime pTime;
    
    try {
        boost::posix_time::time_input_facet* facet = new boost::posix_time::time_input_facet;
        facet->format("%Y-%m-%d %H:%M:%S");
        
        std::istringstream iss(timeStr);
        iss.imbue(std::locale(iss.getloc(), facet));
        iss >> pTime;
    } catch (const std::exception& e) {
        std::cerr << "Failed to parse the input string: " << e.what() << std::endl;
        return 1;
    }

    std::cout << "Method 4 Output: " << pTime << std::endl;

    return 0;
}
  • In this method, we use Boost.DateTime to parse the time string.
  • We create a boost::posix_time::time_input_facet object, which defines the expected input format.
  • We then imbue the std::istringstream with this facet to ensure the correct parsing of the time string.
  • If parsing fails, we catch any exceptions thrown and display an error message.

Output:

Method 4 Output: 2023-Nov-06 15:30:00

Conclusion:

In this blog, we have covered multiple methods to convert a string to a time object in C++. Here's a quick summary:

  • Method 1 utilizes std::tm and std::istringstream for parsing and formatting time strings. It's straightforward and built into the C++ standard library.

  • Method 2 is a variation of Method 1 that uses std::put_time for formatting. It provides more control over the output format.

  • Method 3 uses the <chrono> library to represent time points. This method is more modern and offers greater flexibility in working with time, but it may be slightly more complex.

  • Method 4 involves using third-party libraries like Boost.DateTime, which can handle more advanced time parsing and formatting requirements. It's a good choice for complex scenarios.

Comments (0)

There are no comments. Be the first to comment!!!