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
case 1:
As per your given sample output, you are not including the number of days in the current month.Below is the program,
#include<bits/stdc++.h>
using namespace std;
int a[]={0,31,59,90,120,151,181,212,243,273,304,334,365};
class MyDate{
private:
int day,month,year,duration;
public:
void setValues(int d,int m,int y)
{
day=d;
month=m;
year=y;
calculateDuration();
}
int getDuration()
{
return duration;
}
void calculateDuration()
{
duration=a[month-1];
}
};
int main()
{
string s;
cout<<"Enter Date: ";
cin>>s;
int d=(s[0]-'0')*10+s[1]-'0';
int m=(s[3]-'0')*10+s[4]-'0';
int y=(s[6]-'0')*1000+(s[7]-'0')*100+(s[8]-'0')*10+(s[9]-'0');
MyDate o;
o.setValues(d,m,y);
cout<<"\nNo of days since Jan 1 of the current year : "<<o.getDuration();
}
case 2:
Below is the program in which we include the number of days in the current month.
#include<bits/stdc++.h>
using namespace std;
int a[]={0,31,59,90,120,151,181,212,243,273,304,334,365};
class MyDate{
private:
int day,month,year,duration;
public:
void setValues(int d,int m,int y)
{
day=d;
month=m;
year=y;
calculateDuration();
}
int getDuration()
{
return duration;
}
void calculateDuration()
{
duration=a[month-1]+day;
}
};
int main()
{
string s;
cout<<"Enter Date: ";
cin>>s;
int d=(s[0]-'0')*10+s[1]-'0';
int m=(s[3]-'0')*10+s[4]-'0';
int y=(s[6]-'0')*1000+(s[7]-'0')*100+(s[8]-'0')*10+(s[9]-'0');
MyDate o;
o.setValues(d,m,y);
cout<<"\nNo of days since Jan 1 of the current year : "<<o.getDuration();
}
Comments
Leave a comment