Convert date in string to Date changing format in C
Check if your system has the function strptime
. It's part of POSIX and will do the parsing of the string for you. To convert in the opposite direction there's the C standard function strftime
.
Building a date string in c
I would consider using ctime and/or strftime. It might get you what you want without messing too much with strings and time fields.
With strftime:
char text[100];
time_t now = time(NULL);
struct tm *t = localtime(&now);
strftime(text, sizeof(text)-1, "%d %m %Y %H:%M", t);
printf("Current Date: %s", text);
Convert string to time_t in c
If the non-standard C function strptime() allowed:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
// Return -1 on error
time_t DR_string_to_time(const char *s) {
// Get current year
time_t t = time(NULL);
if (t == -1) {
return -1;
}
struct tm *now = localtime(&t);
if (now == NULL) {
return -1;
}
// Assume current year
struct tm DR_time = {.tm_year = now->tm_year, .tm_isdst = -1};
if (strptime(s, "%b %d %H:%M", &DR_time) == NULL) {
return -1;
}
t = mktime(&DR_time);
return t;
}
Note: "%b %d %H:%M"
(month, day, hour, minute) does not contain the year, so code needs some year to form a time_t
.
How to convert C date string into an integer?
How to convert C date string into an integer?
Compare correctly
As OP's date strings are in chronological and lexicographical order, a conversion is not needed (unless one has negative years).
// if (date1 < date2 < date3){
if (strcmp(date1, date2) < 0 && strcmp(date2, date3) < 0) {
Convert string to time_t
If one wants to still convert, use sscanf()
to parse the string. Pay special attention to possible errors.
Some somewhat tested code:
#include <time.h>
time_t YMD_to_time(const char *ymd) {
if (ymd == NULL) {
return (time_t)-1;
}
struct tm tm = {0}; // Important: initialize all members to 0
int n = 0;
sscanf(ymd, "%4d-%2d-%2d %n", &tm.tm_year, &tm.tm_mon, &tm.tm_mday, &n);
// Scan incomplete or extra junk?
if (n == 0 || ymd[n]) {
return (time_t)-1; // Mal-formed string
}
// Could add extra checks for months/days outside primary range, spaces in string, etc.
// Adjust ranges as struct tm uses different references
tm.tm_year -= 1900;
tm.tm_mon--;
tm.tm_isdst = -1; // Important to get right time for Year-Month-Day 00:00:00 _local time_
// The following conversion assumes tm is in local time.
return mktime(&tm); // This may return -1;
}
Usage
time_t t1 = YMD_to_time(date1);
time_t t2 = YMD_to_time(date2);
time_t t3 = YMD_to_time(date3);
if (t1 == -1 || t2 == -1 || t3 == -1) return times_are_not_comparable
if (t1 < t2 && t2 < t3) return times_are_in_order;
return times_not_in_order;
How convert string to datetime c++?
To access date and time related functions and structures, you would need to include header file in your C++ program.
There are four time-related types: clock_t, time_t, size_t, and tm. The types clock_t, size_t and time_t are capable of representing the system time and date as some sort of integer.
The structure type tm holds the date and time in the form of a C structure having the following elements:
struct tm {
int tm_sec; // seconds of minutes from 0 to 61
int tm_min; // minutes of hour from 0 to 59
int tm_hour; // hours of day from 0 to 24
int tm_mday; // day of month from 1 to 31
int tm_mon; // month of year from 0 to 11
int tm_year; // year since 1900
int tm_wday; // days since sunday
int tm_yday; // days since January 1st
int tm_isdst; // hours of daylight savings time
}
Considering that you have the data string in the following format "YYY-MM-DD HH:MM:SS", the subsequent code below show how to convert the string in a date structure:
#include <iostream>
#include <ctime>
#include <string.h>
#include <cstdlib>
using std::cout;
using std::endl;
int main(int argc, char* argv[])
{
char date[] = "2012-05-06 21:47:59";
tm *ltm = new tm;
char* pch;
pch = strtok(date, " ,.-:");
ltm->tm_year = atoi(pch); //get the year value
ltm->tm_mon = atoi(strtok(NULL, " ,.-:")); //get the month value
ltm->tm_mday = atoi(strtok(NULL, " ,.-:")); //get the day value
ltm->tm_hour = atoi(strtok(NULL, " ,.-:")); //get the hour value
ltm->tm_min = atoi(strtok(NULL, " ,.-:")); //get the min value
ltm->tm_sec = atoi(strtok(NULL, " ,.-:")); //get the sec value
// print various components of tm structure.
cout << "Year: "<< ltm->tm_year << endl;
cout << "Month: "<< ltm->tm_mon<< endl;
cout << "Day: "<< ltm->tm_mday << endl;
cout << "Time: "<< ltm->tm_hour << ":";
cout << ltm->tm_min << ":";
cout << ltm->tm_sec << endl;
delete ltm;
return 0;
}
Output:
Year: 2012
Month: 5
Day: 6
Time: 21:47:59
Related Topics
Why Does Std::Array Not Have an Constructor That Takes a Value for the Array to Be Filled With
How to 'Cout' the Correct Number of Decimal Places of a Double Value
How to Have Multiple Parameter Packs in a Variadic Template
Sendinput() Not Equal to Pressing Key Manually on Keyboard in C++
C++17 Class Template Partial Deduction
How to Build and Use Google Tensorflow C++ API
Is There a Range Class in C++11 for Use with Range Based for Loops
Why Would Someone Use #Define to Define Constants
Do Class/Struct Members Always Get Created in Memory in the Order They Were Declared
Winapi Sleep() Function Call Sleeps for Longer Than Expected
How to Check What Shared Libraries Are Loaded at Run Time for a Given Process
(How) How to Count the Items in an Enum
C++ Compiler Error C2280 "Attempting to Reference a Deleted Function" in Visual Studio 2013 and 2015
How to Know If a Pointer Points to the Heap or the Stack
When Would Anyone Use a Union? Is It a Remnant from the C-Only Days