Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In C++, write code doing the following. The format of a date needs to be changed

ID: 3829353 • Letter: I

Question

In C++, write code doing the following. The format of a date needs to be changed in the following manner: 1st Mar 1984 => 1984-03-01

Write a function 'ReformatDate' which will take the input String and returns the new format of the string.

String ReformatDate(String oldDate);

Example:

1st Mar 1984 => 1984 - 03 - 01

2nd Feb 2013 => 2013 - 02 - 02

15th Apr 1840 => 1840 - 04 - 15

The 'Day' may equal any one of the following values:

1st, 2nd, 3rd, 4th, 5th, 6th, 7th, 8th, 9th,.......29th, 30th, 31st

The 'Month' may equal any one of the following values:

Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec

The Year will always be represented by 4 digits and may equal anything between 1900 and 2100, both inclusive.

Your Task is to format the given list of dates in to the following format: YYYY-MM-DD

Where:

YYYY represents the year in 4 digits

MM represents the year in 2 digits

DD represents the day in 2 digits

Explanation / Answer

#include<iostream>
#include<string>
#include<cstdio>

using namespace std;

string dateRefactor(string date) {
   int day = 0, month
, year = 0;
   string months[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
   int i;
   for (i = 0; i<date.length(); i++) { //extrat integer part of day and conver to integer
       if (date[i] >= '0' && date[i] <= '9')
           day = day*10 + date[i] - '0';
       else
           break;
   }
   i = i + 3; //i now point s to start char of month
   for(month = 1; month<=12; month++) { //match month with the content of the array to detrmine the month in number
       if (months[month-1].compare(date.substr(i,3)) == 0)
           break;
   }

   //i = i + 4 //i now point s to start char of year
   for (i = i + 4 ; i<date.length(); i++) { //extrat integer part of year and conver to integer
       if (date[i] >= '0' && date[i] <= '9')
           year = year *10 + date[i] - '0';
       else
           break;
   }  

   string refacDate = "";
   char rd[20];
   sprintf(rd, "%d - %02d - %02d", year, month, day);
   refacDate = refacDate + rd;
   return refacDate;
}


int main() {
   cout<<dateRefactor("2nd Feb 2013"); //to test

}

I tried my best to keep the code clean and easy. I commented almost every line to make your life easy. If incase you are still facing any problem with the code, please feel free to comment below. I shall be glad to help you with the code