Write a program in C++ to accept date in dd:mm:yyyy format. Store these values in MyDate Class
with members as day, month and year. Convert this date into one variable “Duration” of the current
years. This duration means number of days passed in the current year since Jan 1.
Hint :Use type conversion method from class type to basic type conversions.
Note: consider days in February as 28 for all years.
Output expected:
Enter Date : 05:04:2021
No of days since Jan 1 of the current year : 90
#include <iostream>
#include <string>
using namespace std;
class MyDate
{
public:
void setDate(string data_user)
{
day = stoi(data_user.substr(0,2));
month = stoi(data_user.substr(3, 2));
year = stoi(data_user.substr(6, 4));
}
string getDate()
{
string res = "";
if (day < 10)
{
res += "0";
}
res += (to_string(day) + ":");
if (month < 10)
{
res += "0";
}
res += (to_string(month) + ":");
res += to_string(year);
return res;
};
int getDuration()
{
duration += day;
for (int i = 0; i < month - 1; i++)
{
duration += month_day[i];
}
return duration;
}
MyDate(string data_user)
{
setDate(data_user);
}
private:
int day;
int month;
int year;
int duration{ 0 };
int month_day[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
};
int main()
{
MyDate test("05:04:2021");
cout << test.getDate() << endl;
cout << "No of days since Jan 1 of the current year: " << test.getDuration() << endl;
return 0;
}
Comments
Leave a comment