Date and Time Parsing in C++
Last Updated :
22 Sep, 2023
The Date and time parsing is a common task in programming especially when dealing with user input or data from external sources. C++ provides various utilities and libraries to handle date and time parsing efficiently. Some of the most commonly used libraries for date and time parsing in C++ are:
- <ctime>: This header provides functions and types to work with date and time values including parsing and formatting.
- <chrono>: This header provides facilities to deal with the duration time points and clocks. It is part of the C++11 standard and provides a more modern and type-safe approach to handling date and time operations.
Parsing in <ctime>
The C++ <ctime> is inherited from C language and primarily uses the time_t data type to represent time.
1. Converting date-time string to time_t type.
It is a function to parse a date or time string.
Syntax:
time_t parseDateTime(const char* datetimeString, const char* format);
Here,
- time_t: It is an arithmetic type that is used to represent time in C++.
- parseDateTime: User-defined name of our function.
- dateTimeString: Parameter which represents the current date and time in human-readable form.
- format: The fashion in which dateTimeString is represented.
2. Converting time_t arithmetic type to string
Function to format a time_t value into a date or time string.
Syntax:
string formatDateTime(time_t time, const char* format)
Here,
- string: return type of
- time: It is time in time_t format.
- datetimeString: String representing date and time.
- format: format of the datetime string.
C++ Program:
C++
// C++ Program to implement Date and Time parsing using
// <ctime>
#include <ctime>
#include <iostream>
using namespace std;
// function to parse a date or time string.
time_t parseDateTime(const char* datetimeString, const char* format)
{
struct tm tmStruct;
strptime(datetimeString, format, &tmStruct);
return mktime(&tmStruct);
}
// Function to format a time_t value into a date or time string.
string DateTime(time_t time, const char* format)
{
char buffer[90];
struct tm* timeinfo = localtime(&time);
strftime(buffer, sizeof(buffer), format, timeinfo);
return buffer;
}
int main()
{
const char* datetimeString = "2023-06-17 12:36:51";
const char* format = "%Y-%m-%d %H:%M:%S";
time_t parsedTime = parseDateTime(datetimeString, format);
string formattedTime = DateTime(parsedTime, format);
cout << "Parsed Time--> " << parsedTime << endl;
cout << "Formatted Time--> " << formattedTime << endl;
return 0;
}
OutputParsed Time--> 1687005411
Formatted Time--> 2023-06-17 12:36:51
Parsing in <chrono>
The <chrono> library was introduced in C++11 and provides a modern solution for time manipulation in C++.
1. Converting date-time string to time_point representation.
It is a function to parse a date or time string.
Syntax:
chrono::system_clock::time_point parseDateTime(const std::string& datetimeString, const std::string& format)
Here,
- chrono::system_clock::time_point: It represents time at an instance.
- parseDateTime: User-defined name of our function.
- dateTimeString: Parameter which represents the current date and time in human-readable form.
- format: The fashion in which dateTimeString is represented.
2. Converting time_point representation to string
Function to format a time_point into a date or time string.
Syntax:
string formatDateTime(const chrono::system_clock::time_point& timePoint, const std::string& format);
Here,
- string: return type of
- time: It is time in time_t format.
- datetimeString: String representing date and time.
- format: format of the datetime string.
Implementation
C++
// C++ Program to implement Date and Time Parsing using
// chrono
#include <chrono>
#include <ctime>
#include <iomanip>
#include <iostream>
using namespace std;
// function to parse a date or time string.
chrono::system_clock::time_point GFG(const string& datetimeString, const string& format)
{
tm tmStruct = {};
istringstream ss(datetimeString);
ss >> get_time(&tmStruct, format.c_str());
return chrono::system_clock::from_time_t(
mktime(&tmStruct));
}
// Function to format a time_t value into a date or time string.
string DateTime(const chrono::system_clock::time_point& timePoint,
const string& format)
{
time_t time
= chrono::system_clock::to_time_t(timePoint);
tm* timeinfo = localtime(&time);
char buffer[70];
strftime(buffer, sizeof(buffer), format.c_str(),
timeinfo);
return buffer;
}
int main()
{
const string datetimeString = "2023-05-22 12:24:52";
const string format = "%Y-%m-%d %H:%M:%S";
chrono::system_clock::time_point parsedTime
= GFG(datetimeString, format);
string formattedTime = DateTime(parsedTime, format);
cout << "Parsed Time---> "
<< chrono::system_clock::to_time_t(parsedTime)
<< endl;
cout << "Formatted Time---> " << formattedTime << endl;
return 0;
}
OutputParsed Time---> 1684758292
Formatted Time---> 2023-05-22 12:24:52
Conclusion
The Date and time parsing in C++ can be accomplished using either the <ctime> library or the std::chrono library. <ctime> approach works with time_t values. while the std::chrono approach utilizes std::chrono::system_clock::time_point. Both approaches allow parsing and formatting date and time strings with the custom formats.
Similar Reads
C++ Program to Print Current Day, Date and Time In order to facilitate finding the current local day, date, and time, C++ has defined several functions in the header file, so functions that will help us in achieving our objective of finding the local day, date, and time are: time(): It is used to find the current calendar time.Its return type is
2 min read
strftime() function in C/C++ strftime() is a function in C which is used to format date and time. It comes under the header file time.h, which also contains a structure named struct tm which is used to hold the time and date. The syntax of strftime() is as shown below : size_t strftime(char *s, size_t max, const char *format, c
3 min read
Designated Initializers in C++ 20 With C++20, we get a convenient way of initializing data members. The new feature is called Designated Initializers and it might be familiar to C programmers. In other words, Designated Initializers are a new feature that has been introduced in C++20. It allows developers or programmers to initiate
5 min read
Print system time in C++ (3 different ways) First Method Printing current date and time using time() Second Method CPP // CPP program to print current date and time // using time and ctime. #include <stdio.h> #include <stdlib.h> #include <time.h> int main() { // declaring argument of time() time_t my_time = time(NULL); // ct
2 min read
Print calendar for a given year in C++ Prerequisite : Find day of the week for given dateProblem: To print the calendar of any given year. The program should be such that it can prints the calendar of any input year.Implementation: CPP // A C++ Program to Implement a Calendar // of an year #include<bits/stdc++.h> using namespace st
6 min read
localtime() function in C++ The localtime() function is defined in the ctime header file. The localtime() function converts the given time since epoch to calendar time which is expressed as local time. Syntax: tm* localtime(const time_t* time_ptr); Parameter: This function accepts a parameter time_ptr which represents the poin
1 min read
mktime() function in C++ STL The mktime() is an inbuilt C++ function which converts the local calendar time to the time since epoch and returns the value as an object of type time_t. Syntax : time_t mktime( struct tm *time_ptr ) Parameters: The function accepts a mandatory parameter pointer time_ptr that points to a tm object s
2 min read
How to sort an array of dates in C/C++? Given an array of dates, how to sort them. Example: Input: Date arr[] = {{20, 1, 2014}, {25, 3, 2010}, { 3, 12, 1676}, {18, 11, 1982}, {19, 4, 2015}, { 9, 7, 2015}} Output: Date arr[] = {{ 3, 12, 1676}, {18, 11, 1982}, {25, 3, 2010}, {20, 1, 2014}, {19, 4, 2015}, { 9, 7, 2015}} We strongly recommend
3 min read
How to Measure Elapsed Time in C++? Measuring elapsed time is a common requirement for most software development packages. It is used to determine the efficiency of the program and gives an idea of which parts of the program takes which much time. This helps in optimizing the code, such that improves its execution time. In this articl
3 min read
Add given timestamps by overloading + operator in C++ Time Class In C++, we can make operators to work for user-defined classes. This means C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator overloading.In this article, we will overload an operator â+â in the Time class so that we can concatenate
3 min read