Code Snippets C/C++ Code Snippets

C program to get yesterday’s (previous day) date.

By: IncludeHelp, On 04 OCT 2016

In this program we will learn how to get previous day’s (yesterday’s) date when current day’s date is given?

In this example we will read any date (we are reading current day’s date) and program will provide you the previous day’s date i.e. yesterday’s date.

We created a structure date which has dd, mm and yy as structure parameters; we will read and print the date value using date structure.

To get previous day’s date we are using a user define function getYesterdayDate() which has date structure as pointer, any changes made in the structure date inside this function will reflect to the actual values in the main().

C program (Code Snippet) – To get Previous Day’s Date (Yesterday’s Date)

Let’s consider the following example:

/*C program to get yesterday’s (previous day) date.*/

#include <stdio.h>

//declaration of date structure
struct date{
	short dd,mm,yy;
};

//function to get yesterday's (previous) date
void getYesterdayDate(struct date *d){
	if(d->dd==1){
		if(d->mm==4||d->mm==6||d->mm==9||d->mm==11){
			d->dd=31;
			d->mm--;
		}
		else if(d->mm==3){
			if((d->yy%4)==0) d->dd=29;
			else d->dd=28;
			d->mm--;
		}
		else if(d->mm==1){
			d->dd=31;
			d->yy--;
		}
		else if(d->mm==2){
			d->dd=31;
			d->mm--;
		}
		else{
			d->dd=30;
			d->mm--;
		}
	}
	else{
		d->dd--;
	}
}
int main(){
	//date structure variable declaration
	struct date dt;
	
	//read date
	printf("Enter date in dd/mm/yyyy format: ");
	scanf("%d/%d/%d",&dt.dd,&dt.mm,&dt.yy);
	
	//print current date
	printf("Entered current date is: ");
	printf("%02d/%02d/%02d\n",dt.dd,dt.mm,dt.yy);
	
	//get previous (yesterday) date
	getYesterdayDate(&dt);

	//print yesterday's date
	printf("Previous (Yesterday's)  date is: ");
	printf("%02d/%02d/%02d\n",dt.dd,dt.mm,dt.yy);	
	
	return 0;	
}

Output

            First Run:
            Enter date in dd/mm/yyyy format: 10/4/2016
            Entered current date is: 10/04/2016 
            Previous (Yesterday's)date is: 09/04/2016 

            Second Run:
            Enter date in dd/mm/yyyy format: 31/3/2016
            Entered current date is: 31/03/2016 
            Previous (Yesterday's)date is: 30/03/2016 

            Third Run:
            Enter date in dd/mm/yyyy format: 01/3/2016
            Entered current date is: 01/03/2016 
            Previous (Yesterday's)date is: 29/02/2016 

            Fourth Run:
            Enter date in dd/mm/yyyy format: 1/12/2016
            Entered current date is: 01/12/2016 
            Previous (Yesterday's)date is: 30/11/2016 

            Fifth Run:
            Enter date in dd/mm/yyyy format: 1/1/2016 
            Entered current date is: 01/01/2016 
            Previous (Yesterday's)date is: 31/01/2015        
        




Copyright © 2024 www.includehelp.com. All rights reserved.