• Register
search
Log In

Date is  an essential and every person uses their different formats of the date. But the ISO 8601 specifies a format of dd/mm/yyyy. Since 01/04/2003 is more clearer than 01/02/03. Some prefer to modify it by using an abbreviation for the month to make it more clear, like 01-April-2003, but then it is no longer neutral i.e., used in general. We are going to write a program that prints the dd/mm/yyyy format which is a string into different sections as int.

 

Approach

  • Define the string date and int mm,dd,yyyy

  • Ask for the input

  • Check if it is in correct format which is dd/mm/yyyy

  • Run three different for loops for getting the values of day, month and year

  • Storing the values in the integer variables which were created previously, by casting/converting string into int

  • Printing the output

#include <iostream>
#include <string.h>
using namespace std;

int main()
{
char date[11]; // mm/dd/yyyy
int mm, dd, yyyy;

cout<<"Enter date : ";
cin>>date;

if(strlen(date)<10 || strlen(date)>10 )
{
cout<<"\n Error:Input should be in mm/dd/yyyy format";
}
else if(strlen(date) == 10)
{
char m[3], d[3], y[5];
int i,j;
	
for( i = 0; i<2; i++)
m[i]=date[i];     

for(i = 3, j=0; i<5; i++,j++){
d[j]=date[i];
}
for(i = 6, j=0; i<10; i++, j++)
y[j]=date[i];

mm = atoi(m);
dd=atoi(d);
yyyy = atoi(y);

cout<<"\n Month : "<<mm;
cout<<"\n Day : "<<dd;
cout<<"\n Year : "<<yyyy;
}
else
{
cout<<"\n Error:Input should be in mm/dd/yyyy format";
}
return 0;
}

Output

If format is correct

Enter date : 12/12/2020


 Month : 12

 Day : 12

 Year : 2020

 

If format is incorrect

Enter date : 12122020


 Error:Input should be in mm/dd/yyyy format

 

Fun fact

ISO 8601 is computer friendly. (Doing a standard character sort on a list of dates gives you a chronologically ordered list) ISO 8601 is unfriendly for people since people like the neutral method.

posted Jun 23 in c++ 100 points