string s = v[2];
string result = s.substr(s.find_last_of("modify=") + 1, 14);
cout << result;//output MDTM boost.txt 20150911115551
i want convert like this YYYY-MM-DD HH:MM
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
I have been trying to figure out how to accurately subtract one date from another in C++. Both will be received through user input. I thought that by creating a class, along with the use of <ctime>, I would be able to do this but I have yet to find how to do so while taking Leap years into consideration, which would be the cause for the loss of accuracy that it might have.
Here is how I was approaching the task:
#include "pch.h"
#include <iostream>
#include <ctime>
using namespace std;
class Year {
private:
struct tm date3;
struct tm date2;
struct tm date;
int FirstYear, SecondYear;
int FirstMonth, SecondMonth;
int FirstDay, SecondDay;
public:
int DateCalculus(struct tm* date, struct tm* date2);
void ResultShown();
};
int Year::DateCalculus(struct tm* date, struct tm* date2) {
struct tm date3;
date3.tm_year = date->tm_year - date2->tm_year;
date3.tm_mon = date->tm_mon - date2->tm_mon;
date3.tm_mday = date->tm_mday - date2->tm_mday;
}
void Year::ResultShown() {
cout<< date3;
}
int main() {
struct tm Date = { 0, 0, 12 };
struct tm Date2 = { 0, 0, 12 };
int Firstyear, SecondYear;
int Firstmonth, SecondMonth;
int Firstday, SecondDay;
cin >> Firstday; cout << "Day 1 " << endl;
cin >> Firstmonth; cout << "Month 1 " << endl;
cin >> Firstyear; cout << "Year 1 " << endl;
cin >> SecondDay; cout << "Day 2 " << endl;
cin >> SecondMonth; cout << "Month 2 " << endl;
cin >> SecondYear; cout << "Year 2 " << endl;
Date.tm_year = Firstyear;
Date.tm_mon = Firstmonth;
Date.tm_mday = Firstday;
Year::DateCalculus(&Date, &Date2);
cout << asctime(&Date2) << std::endl;
return 0;
}
I need to print out dates in four formats when a user enters a month, day and year.
For example if I enter "sept" for month, 17 for day and 1921 for year, it will print out:
1) 9/17/1921
2) September 17,1921
3) 1921-9-17
4) 1921-sep-17
I also do validation where if the number of days is less than 1 or greater than than the number of days for that month and the year cannot be less than 1900 or greater than 2020. If it is, month gets defaulted to "January" day to 1 and year to 2001.
When I enter jan for month 5 for day 2005 for year, I get weird values in my console 1/-858993460/-858993460 and then terminates. But when I enter mar 5 2005 i get
3/5/2005
March2005
ory corruption5
ory corruptionmar-5
I create an instance of Date and call a 3 argument constructor. The 3 argument constructor then calls a validate function which return a boolean. If the return value is false, it will call the default constructor which sets everything to january 1 2001.
//UPDATE:
Changed inital value of int index in date.cpp to -1 instead of NULL. Doing this now calls the print function four times four when I enter "jan" but I still get the weird results
1/5/2005
January2005 //This should be January 5, 2005
ory corruption5
ory corruptionmar-5
Why does the first time print is called all my member variables retain the values, but the 2nd, 3rd, and 4th time, day is missing and shows weird corruption message?
I don't know what is going on but when I also enter an invalid date such as "jan" for month but 36 for days and 2025 for year, the default constructor should set month to January, day to 1 and year to 2001 but I get garbage values
1/-858993460/-858993460
This is the first time print is called then after that it terminates.
//Header
#pragma once
#include <iostream>
#include <string>
using namespace std;
/*Add more constants if needed*/
#ifndef DATE_H
#define DATE_H
enum DateFormat { mdy1, mdy2, ymd1, ymd2 };
const int MIN_YEAR = 1900;
const int MAX_YEAR = 2020;
const string monthStr[] = //alternative: const char monthStr[] [15]=
{ "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November",
"December" };
const string monthStrAbbrev[] = //not strictly necessary, but helpful
{ "jan", "feb", "mar", "apr", "may", "jun",
"jul", "aug", "sep", "oct", "nov",
"dec" };
const int monthDays[] =
{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
class Date {
private:
string month;
int day, year;
bool validateDate(string, int, int);
Date();
public:
Date(string, int, int);
void print(DateFormat type);
};
#endif // !DATES_H
//Dates.cpp
#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include "date.h"
using std::cout;
using std::cin;
int global;
Date::Date() : month("January"), day(1), year(2001) { cout << "INSIDE CONST" << endl; }
Date::Date(string m, int d, int y)
{
if (!validateDate(m, d, y))
{
cout << "IF FALSE" << endl;
Date();
}
else
{
month = m;
day = d;
year = y;
cout << "MONTH IS :" << month << " DAY IS: " << day << " YEAR IS: " << year << endl;
}
}
bool Date::validateDate(string m, int d, int y)
{
cout << "size is " << sizeof(monthStrAbbrev) / sizeof(monthStrAbbrev[0]) << endl;;
int index = -1;
for (int x = 0; x < 11; x++)
{
string mAbr = monthStr[x].substr (0, 3);
transform(mAbr.begin(), mAbr.end(), mAbr.begin(), (int(*) (int)) tolower);
cout << "Abbr: " << mAbr << endl;
if (m == mAbr)
{
index = x;
global = x;
cout << "x " << x << " global " << global << " Index " << index << endl;
if (d < 1 && d > monthDays[index])
{
cout << "FALSE 1" << endl;
return false;
}
if (y < MIN_YEAR || y > MAX_YEAR)
{
cout << "FALSE 2" << endl;
return false;
}
break;
}
}
if (index == -1)
{
cout << "IF NULL" << endl;
return false;
}
else
{
cout << " IF NOT NULL" << endl;
return true;
}
}
void Date::print(DateFormat type)
{
if (type == mdy1)
{
cout << global + 1 << "/" << day << "/" << year << endl;
}
else if (type == mdy2)
{
cout << monthStr[global] << day + ", " << year << endl;
}
else if (type == ymd1)
{
cout << year + "-" << (global + 1) + "-" << day << endl;
}
else if (type == ymd2)
{
cout << year + "-" << month + "-" << day << endl;
}
}
//Test.cpp
#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
#include "date.h"
void setDateValues(string&, int&, int&);
int main()
{
string mth;
int day, yr;
setDateValues(mth, day, yr);
transform(mth.begin(), mth.end(), mth.begin(), (int(*) (int)) tolower);
Date d1(mth, day, yr);
cout << "Date is:\n";
DateFormat type;
type = mdy1;
d1.print(type);
type = mdy2;
d1.print(type);
type = ymd1;
d1.print(type);
type = ymd2;
d1.print(type);
return 0;
}
void setDateValues(string & m, int& d, int& y)
{
cout << "Enter month: ";
cin >> m;
cout << "Enter day: ";
cin >> d;
cout << "Enter year: ";
cin >> y;
}
There is a standard library function for this: strftime().
You give it a date in a struct, and it writes a string. For your four cases, the format strings would be:
1) %m/%d/%Y
2) %B %d, %Y
3) %F
4) %Y-%b-%d
I'm brand new to C++. In my Programming I class, I've been given the following assignment as a midterm:
-Calculate how many days you have been alive
(epoch time from 01/01/1970 stored by seconds)
-Command Line Args for Birth Year, Birth Month, Birth Day
Now, I've already figured out the function itself for actually subtracting two dates from each other, and I've figured out how to grab the current date and stick it in that function. The problem I'm having is how to get the user's entered date and send that to the function.
I've been playing with a "test" piece of code to get this to work, unfortunately when I try to compile this I just get a MOUNTAIN of errors that I don't understand at all, so I'm clearly doing something wrong.
#include <iostream>
#include <ctime>
using namespace std;
struct tm a(int year, int month, int day)
{
struct tm birth {0};
cin >> year >> endl;
cin >> month >> endl;
cin >> day >> endl;
birth.tm_year = year - 1900;
birth.tm_mon = month;
birth.tm_mday = day;
return birth;
}
int main()
{
int year, month, day;
cout << "Enter a year, month, and day: " << endl;
cin >> year >> month >> day >> endl;
tm a(year, month, day);
time_t x = mktime(&a);
time_t y = time(0);
if ( x != (time_t)(-1) && y != (time_t)(-1) )
{
double difference = difftime(y, x) / (60 * 60 * 24);
cout << ctime(&x);
cout << ctime(&y);
cout << "difference = " << difference << " days" << endl;
}
return 0;
}
I've tried googling some of these errors, and the results I'm seeing keep talking about "pointers". I have no clue what pointers are, and flipping through our textbook, it looks like something that's about three or four chapters ahead of where we are now. I tried asking my professor about this the other day, and he just sort of giggled and said something to the effect of "Well yeah, that's the point of the midterm." I don't understand if that means I'm supposed to figure out pointers on my own or if I'm not supposed to use them.
I'm trying to get a year, month, and day from arguments entered by the user at the point of execution and stick them into a struct tm so that my function at the bottom will work.
EDIT: I figured out that I am trying to use the struct like a function, which is wrong. I have made the following changes:
#include <iostream>
#include <ctime>
using namespace std;
struct tm bday(int year, int month, int day)
{
struct tm r {0};
r.tm_year = year - 1900;
r.tm_mon = month;
r.tm_mday = day;
return r;
}
int main()
{
int year, month, day;
cout << "Enter a year, month, and day: " << endl;
cin >> year >> endl;
cin >> month >> endl;
cin >> day >> endl;
struct tm a = bday(year, month, day);
time_t x = mktime(&a);
time_t y = time(0);
if ( x != (time_t)(-1) && y != (time_t)(-1) )
{
double difference = difftime(y, x) / (60 * 60 * 24);
cout << ctime(&x);
cout << ctime(&y);
cout << "difference = " << difference << " days" << endl;
}
return 0;
}
Now getting the following errors when compiling:
filename.cpp:22:17: error: no match for 'operator>>'
filename.cpp:23:18: error: no match for 'operator>>'
filename.cpp:24:16: error: no match for 'operator>>'
This is not correct:
cin >> year >> endl;
You cannot read anything into endl. You probably confused input with output where std::cout << x << std::endl; is a common pattern. However, as a sidenote, you dont need endl after each line for output either. endl not only adds a newline character, but also flushes the stream. If you just want to start a new line then use \n only.
I have a requirement to get time interval until end of month in C++. Are there any C++ APIs which can easily do that for me?
I need to start a timer which will expire at the first day of next month at 00:00:00 hours. For that, I need to compute the time interval i.e. number of seconds from now till end of this month.
Its rather straight foward. Get the difference in number of days between now and the last day of the month. Then get the number of seconds in a day.
Now you have the number of seconds till the end of the month, now subtract that with the number of seconds right now so far today and you will get the number of seconds until the end of the month.
#include <time.h>
#include <iostream>
using namespace std;
int main(){
int day1,month1,year1;
int day2,month2,year2;
int i,temp,DaysDiff=0;
int month[]={31,28,31,30,31,30,31,31,30,31,30,31};
int totalDiffDaysSecs=0;
int nowSeconds=0;
int expire=1000;
time_t t = time(0); // get time now
struct tm * now = localtime( & t );
cout<<"\n";
day1=now->tm_mday;
month1=(now->tm_mon + 1);
year1=(now->tm_year + 1900);
day2=31;
month2=7;
year2=2015;
temp=day1;
for(i=month1;i<month2+(year2-year1)*12;i++){
if(i>12){
i=1;
year1++;
}
if(i==2){
if(year1%4==0 && (year1%100!=0 || year1%400==0))
month[i-1]=29;
else
month[i-1]=28;
}
DaysDiff=DaysDiff+(month[i-1]-temp);
temp=0;
}
cout <<"Current Time = "<< now->tm_hour << ":" << now->tm_min << "."<<now->tm_sec<<"\n";
cout <<"Today's date "<< (now->tm_year + 1900) << '-' << (now->tm_mon + 1) << '-' << now->tm_mday << " \n";
cout <<"Target date "<< year2 << '-' << month2 << '-' << day2 << " \n";
DaysDiff=DaysDiff+day2-temp;
cout<<"Target Month = "<<i<<"\n";
cout<<"Days in Target month = "<<month[i-1]<<"\n";
cout<<"Days diff Today - Target Month = "<<DaysDiff<<" \n";
totalDiffDaysSecs=DaysDiff*24*60*60;
nowSeconds= (now->tm_hour * 3600) + (now->tm_min * 60)+ now->tm_sec;
cout<<"Total seconds in a day = "<<24*60*60<<" \n";
cout<<"current total seconds so far today = "<< nowSeconds <<"\n";
cout<<"Total number of seconds in "<< DaysDiff <<" days = "<< totalDiffDaysSecs <<"\n";
cout<<"\n\n";
while(expire>0){
t = time(0); // get time now
now = localtime( & t );
nowSeconds= (now->tm_hour * 3600) + (now->tm_min * 60)+ now->tm_sec;
expire=totalDiffDaysSecs - nowSeconds;
cout <<"Seconds until end of month = "<< expire <<" \r";
}
cout<<"\n\n";
cout<<"Countdown expired.\n\n";
return 0;
}
I'm trying to figure out how to get both military and standard time to display.
A User inputs the time, then its shown in its standard form.
It's mostly there, but the standard time portion is giving me a few issues.
#ifndef TIME_H
#define TIME_H
class Time
{
public:
Time(int = 0, int = 0, int = 0);
~Time();
int hour; // valid values are 0 to 23
int minute; // valid values are 0 to 59
int second; // valid values are 0 to 59
void setTime(int, int, int); // function that checks if inputs are valid
void printUniversal(); // prints in HH:MM:SS format
void printStandard(); // prints in HH:MM:SS AM/PM format
static int count; //counter
};
#endif
#include "stdafx.h"
#include "Time.h" //header file that contains the Time class file
#include <iostream>
#include <iomanip>
#include <ctime>
using namespace std;
int Time::count = 12;
Time::Time(int hr, int min, int sec)
{
hour = hr; minute = min; second = sec;
count++;
}
Time::~Time()
{
count--;
}
void Time::setTime(int hr, int min, int sec)
{
hour = (hr >= 0 && hr < 24) ? hr : 0; // checks if hour input is valid
minute = (min >= 0 && min < 60) ? min : 0; // checks if minute input is valid
second = (sec >= 0 && sec < 60) ? sec : 0; // checks if seconds input is valid
}
void Time :: printUniversal()
{
cout << setfill('0') << setw(2) << hour << ":" << setw(2) << minute << ":" << setw(2) << second;
}
void Time::printStandard()
{
cout << ((hour == 0 || hour == 12) ? 12 : hour % 12) << ":" << setfill('0') << setw(2) << minute << ":" << setw(2) << second << (hour < 12 ? " AM" : " PM");
}
//(Where I implement the functions - main.cpp)
#include "Time.h"
#include <iostream>
using namespace std;
int main()
{
int hour, minute, second;
Time t; //t is the time object //(PROBLEM!!!-Dont understand how to write the correct parameters)
//test is also a time object //(PROBLEM!!!-Dont understand how to write the correct parameters)
//Time *tp = new Time;
//Time *tarray = new Time[5];
cout << "Enter hour in military time ";
cin >> hour;
cout << "Enter minute ";
cin >> minute;
cout << "Enter second ";
cin >> second;
cout << "\nThe standard time is ";
t.printStandard(); //(PROBLEM!!!- I have the number 12 appearing right after AM and i can't get rid of it. )
cout << "\nThe universal time is ";
t.printUniversal();
cout << endl;
return 0;
} // end main
Update: The errors are gone for the moment, thanks to the suggestions posted.
However now when I run it, I get this....well since I can't post images yet...
I'll input 13, 45, 05 and almost like a old VCR, I can't 12:00:00 for standard or 00:00:00 for universal
No matter what I input into its all the same output.
Time t(); // This declares a function named t which takes
// no arguments and returns a Time object
Time test(); // This declares a function named test which
// takes no arguments and returns a Time object
Time t; // this is a default constructed Time object named t
Time t( 12, 7, 5 ); // this is a Time object with all
// parameters passed to the constructor
In printStandard, you have
<< sizeof(Time)
This is where the 12 is coming from. Objects of your Time class type take 12 bytes in memory.
I strongly suggest you get a book on C++, as all of this would be explained in there.