I want to know how to find which is bigger date using a C program
kindly help me out plz....
You can use the difftime function:
#include <time.h>
#include <stdio.h>
int main(void) {
time_t date1, date2;
// initialize date1 and date2...
double seconds = difftime(date1, date2);
if (seconds > 0) {
printf("Date1 > Date2\n");
}
return 0;
}
If your dates are not of type time_t, you can use the function mktime to convert them.
#include <stdio.h>
struct date
{
int month;
int date;
int year;
};
int main(void)
{
int i=compare_dates (struct date d1, struct date d2);
switch(i)
{
case -1:
printf("%d/%d/%d is earlear date than %d/%d %d", D1.day, D1.month, D1.year, D2.day
case 1:
printf("%d/%d/%d is later date than %d/%d/%d",D1.day,D1.month,D1.year,D2.day…
case 0:
printf("%d/%d/%d is the same date than %d/%d/%d", D1.day, D1.month, D1.year, D2.day
}
return 0;
}
int compare_dates (struct date d1, struct date d2)
{
if (d1.year < d2.year)
return -1;
else if (d1.year > d2.year)
return 1;
if (d1.year == d2.year)
{
if (d1.month<d2.month)
return -1;
else if (d1.month>d2.month)
return 1;
else if (d1.day<d2.day)
return -1;
else if(d1.day>d2.day)
return 1;
else
return 0;
}
}
If you just want to know which is bigger, you don't need go through all this. You can just prioritize the values and compare them. Just add coefficients to month and year that is bigger than highest day possible. For example, say that a month is 100 times more important than the day and a year is 2000 times more important than a day. Just calculate the score of the dates and compare them.
#include <stdio.h>
int main()
{
int day1, day2, month1, month2, year1, year2;
printf("Enter first date (dd/mm/yyyy) => "); scanf("%d/%d/%d", &day1, &month1, &year1);
int prioritedScore1 = day1 + month1*100 + year1*2000;
printf("Enter second date (dd/mm/yyyy) => "); scanf("%d/%d/%d", &day2, &month2, &year2);
int prioritedScore2 = day2 + month2*100 + year2*2000;
if(prioritedScore1 > prioritedScore2){
printf("Bigger date is => %d/%d/%d", day1, month1, year1);
} else if(prioritedScore2 > prioritedScore1){
printf("Bigger date is => %d/%d/%d", day2, month2, year2);
} else{
printf("Dates are same.");
}
return 0;
}
You can always use a long integer in order to get rid of possible bugs when user enters so high numbers like 2147484 as year.
Can you give more information about what you want to achieve ? Because comparing date is really easy. After all, they are just number of seconds (or milli, micro, nano, ...) since a given past date, or a structure containing year, month, day, ... Whatever the format, the comparison should be pretty easy to perform.
Maybe you want to compare two date given by the user as strings (something like "2011-03-12 18:38") ? Then, you can use strptime to convert the string to a struct tm, and then do the comparison.
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
int parse_date(char* date, struct tm* tm)
{
char* format;
char* formats[] = {
"%F %I", /* "2011-03-12 06:38:05 AM" */
"%F %T", /* "2011-03-12 18:38:05" */
"%F %R", /* "2011-03-12 18:38" */
NULL,
};
for (format = formats[0]; format; ++ format) {
if (strptime(date, format, &tm)) {
return 1;
}
}
return 0;
}
int main(int argc, char** argv)
{
float diff;
char* date1;
char* date2;
struct tm tm1;
struct tm tm2;
time_t time1;
time_t time2;
if (argc != 3) {
fprintf(stderr, "usage: compare-date date1 date2\n");
exit(1);
}
date1 = argv[1];
date2 = argv[2];
if (!parse_date(date1, &tm1)) {
fprintf(stderr, "unsupported date: %s\n", date1);
exit(1);
}
if (!parse_date(date2, &tm1)) {
fprintf(stderr, "unsupported date: %s\n", date2);
exit(1);
}
time1 = mktime(&tm1);
time2 = mktime(&tm2);
diff = difftime(time1, time2);
printf("%s %c %s\n",
date1,
(diff < 0 ? '<' : (diff > 0 ? '>' : '==')),
date2);
return 0;
}
You didn't say in which format you have the date, so I will name two common examples:
If you are using GNU lib-c (or MinGW) and query the time with:
time_t time (time_t *result)
Then time_t is just a long int, numbers of seconds since epoch and you can subtract one date from the other to find out the number of seconds difference.
If you are using the Windows API and have a filetime-structure:
typedef struct _FILETIME {
DWORD dwLowDateTime;
DWORD dwHighDateTime;
} FILETIME, *PFILETIME;
you can cast the pointer to a pointer to ULARGE_INTEGER, and subtract that one giving you the number of 100-nanosecond intervals difference.
Related
#include <stdio.h>
#include <time.h>
int date_txt[5],today_date;
scanf("%d",&today_date); //i enter (input) the date manually e.g. 20171109
date_txt[0]=20161102; // year month day form (rrrrmmdd)
date_txt[1]=20150101;
date_txt[2]=20170615;
date_txt[3]=20160628;
date_txt[4]=20150101;
I have several dates which i need to compare with today_date to see if the difference is equal to or greater than 1 year. I have found that there exists a function for this called difftime(), but as i am a novice i do not know how to exactly do this. Any help is appreciated, thank you.
You can do something like this:
#include <stdio.h>
#include <time.h>
#define COUNT 5
#define SECONDS_NON_LEAP_YEAR (365*24*3600)
#define SECONDS_LEAP_YEAR (366*24*3600)
typedef struct tm T_TIME;
T_TIME dToday, dTemp;
void convertToTime(int iDate, T_TIME* tTime)
{
tTime->tm_mday = iDate%100;
iDate/=100;
tTime->tm_mon = (iDate%100)-1;
iDate/=100;
tTime->tm_year = iDate-1900;
}
int isLeapYear(int yyyy)
{
if(yyyy%100) // Not a century
{
return !(yyyy%4);
}
return !(yyyy%400);
}
int main(void) {
int date_txt[]={20161102, 20150101, 20170615, 20160628, 20150101};
int today_date, i, flg, isThisYearLeap, tSeconds;
scanf("%d",&today_date); //i enter (input) the date manually e.g. 20171109 year month day form (rrrrmmdd)
convertToTime(today_date, &dToday);
isThisYearLeap = isLeapYear(dToday.tm_year+1900);
for(i=0;i<COUNT; i++)
{
convertToTime(date_txt[i], &dTemp);
tSeconds = difftime(mktime(&dToday), mktime(&dTemp));
flg = (isThisYearLeap || isLeapYear(dTemp.tm_year+1900)) ?
(tSeconds >= SECONDS_LEAP_YEAR) : (tSeconds >= SECONDS_NON_LEAP_YEAR);
printf("The difference between Today and date %d is %s 1 year.\n", date_txt[i],
(flg ? "Greater than or equals to" : "Less than"));
}
return 0;
}
See it in execution here
Let's say the user is prompted for the date - e.g. Friday.
How can that string be used to correctly compare with another sting?
#include <stdio.h>
#include <time.h>
int main(void)
{
time_t current_time;
struct tm * time_info;
char timeString[9];
time(¤t_time);
time_info = localtime(¤t_time);
strftime(timeString, sizeof(timeString), "%A", time_info);
printf("%s\n",timeString);
if (timeString == "Friday")
{printf("Weekday");
}
else
{printf("not weekday");
}
return 0;
}
The program keeps printing out not weekday.
Use strncmp() instead of comparing the string with ==:
if (strncmp(timeString,"Friday",7) == 0)
{printf("Weekday");
}
See this in action at tutorialspoint.com:
Friday
Currently, it is Thursday (for ~50% of the world) - so try this one:
Thursday
I have this program, where you enter two dates into two structures (same type), and then I want a function to find which date I entered is the later date. It compares only year and month. Once the later date is found, I want the function to return a pointer to the structure with the later date. I then want to print out the later date.
This is what I have so far, but I get errors and I'm not sure about the pointer syntax.
Code:
#include <stdio.h>
struct date{
int year;
int month;
int day;
};
main()
{
struct date dates[2];
int i = 0, res = 0;
for ( i = 0 ; i < 2 ; i++){
printf("Enter a year!");
scanf("%d", &dates[i].year);
printf("Enter a month!");
scanf("%d", &dates[i].month);
printf("Enter a day!");
scanf("%d", &dates[i].day);
}
res = later(&dates[1], &dates[2]);
}
struct date *later(struct date *one, struct date *two)
{
if (one->year > two->year){
return *one;
}
else if (one->year == two->year){
if(one->month > two->month){
return *one;
}
else
return *two;
}
else {
return *two;
}
}
Error messages:
q4.c:28:3: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat=]
printf("%d", &res);
^
q4.c: At top level:
q4.c:32:14: error: conflicting types for ‘later’
struct date *later(struct date *one, struct date *two){
^
q4.c:26:9: note: previous implicit declaration of ‘later’ was here
res = later(&dates[1], &dates[2]);
^
q4.c:55:1: error: expected identifier or ‘(’ before ‘}’ token
}
There are multiple problem with your program:
There is no prototype for your function later() Solution: Add date *later(date *one, date *two); after ending declaration of struct date or move the whole function above main().
Change return type of you function to date* as you are returning a pointer to date object.
Change data type of res to date* as you want to store a pointer to date object.
Then print the object res is pointing to by printing each of its components individually as printf is not designed to print your custom data type.
This is only a suggestion but i recommend you moving declaration of int i to for(int i = 0; i < 2; i++); it is just considered better and saves memory.
If you want res to be an int you will have to return a object instead of a pointer and then typecast it to int. Guide on typecasting: http://www.cplusplus.com/doc/tutorial/typecasting/
There are a number of ways to handle the return as have been pointed out in the comments. You can either declare your later function as int (as you have), and use the return similar to the return from strcmp (0 - dates are equal, -1 first is earlier than last, 1 first is later than last).
You can also declare later as struct date * and return a pointer to the later date (which leaves you in a pickle as to what to return if the dates are equivalent).
Your return is more meaningful, if you return a int value similar to strcmp. An implementation that compares your struct date and returns -1, 0 or 1 based on the first being earlier, equivalent, or later could be:
int later (struct date *one, struct date *two)
{ /* the ternary operator is your friend */
if (one->year != two->year) /* years differ */
return one->year > two->year ? 1 : -1;
if (one->month != two->month) /* months differ */
return one->month > two->month ? 1 : -1;
if (one->day != two->day) /* days differ */
return one->day > two->day ? 1 : -1;
return 0; /* dates are equivalent */
}
(note: the use of the ternary operator (e.g. test ? if true : if false) to simply comparing each date component)
Also, note, in this case your are free to pass struct date instead of struct date * as the function will work fine operating on a copy of each date struct. It is up to you how you want to do it.
A small sample program testing the function (and noting a few code improvements) could be:
#include <stdio.h>
struct date {
int year;
int month;
int day;
};
int later (struct date *one, struct date *two);
void prn_result (struct date a, struct date b, char op);
/* main is a function of type 'int' and returns a value */
int main (void) {
struct date dates[2] = {{0}}; /* initialize variables */
int i = 0, res = 0;
for (i = 0; i < 2; i++) { /* user input of dates */
printf ("Enter a year: ");
scanf ("%d", &dates[i].year);
printf ("Enter a month :");
scanf ("%d", &dates[i].month);
printf ("Enter a day: ");
scanf ("%d", &dates[i].day);
putchar ('\n');
}
res = later (&dates[0], &dates[1]); /* comparison */
if (res == 0)
prn_result (dates[0], dates[1], '=');
else if (res > 0)
prn_result (dates[0], dates[1], '>');
else
prn_result (dates[0], dates[1], '<');
return 0;
}
int later (struct date *one, struct date *two)
{ /* the ternary operator is your friend */
if (one->year != two->year) /* years differ */
return one->year > two->year ? 1 : -1;
if (one->month != two->month) /* months differ */
return one->month > two->month ? 1 : -1;
if (one->day != two->day) /* days differ */
return one->day > two->day ? 1 : -1;
return 0; /* dates are equivalent */
}
void prn_result (struct date a, struct date b, char op)
{
printf ("%d/%d/%d %c %d/%d/%d\n",
a.month, a.day, a.year, op,
b.month, b.day, b.year);
}
Example Use/Output
$ ./bin/cmpyear
Enter a year: 1993
Enter a month :3
Enter a day: 13
Enter a year: 1993
Enter a month :3
Enter a day: 12
3/13/1993 > 3/12/1993
$ ./bin/cmpyear
Enter a year: 1993
Enter a month :3
Enter a day: 12
Enter a year: 1993
Enter a month :3
Enter a day: 12
3/12/1993 = 3/12/1993
$ ./bin/cmpyear
Enter a year: 1993
Enter a month :3
Enter a day: 12
Enter a year: 1993
Enter a month :3
Enter a day: 13
3/12/1993 < 3/13/1993
Look it over and let me know if you have an further questions.
I'm trying to make a big program for making a Gregorian calendar but at the moment, I'm just trying to work with a function that parses an inputted date. A few of the functions (sscanf and fgets) I'm not really sure how to use them with the rest of the program. Here is my attempt:
int main(int arg, char *argv[]) {
/*
* Request a date from the user
* in format DD-MM-YYYY, DD.MM.YYYY or DD/MM/YYYY
*/
date d;
char input_date[20];
fgets(input_date, 20, stdin);
printf("Enter your date of birth in the form DD/MM/YYYY:");
//fgets(d, 100, stdin);
sscanf(input_date,"%d", &d.day, &d.month, &d.year);
if (leapYearFeb(d.year, d.month)) {
d.day = d.day + 1;
}
if (parse_formatted_date(input_date, &d))
printf("date: %s\ndd = %d, mm = %d, yy = %d\n", input_date, d.day, d.month, d.year);
return 1;
return 0;
}
Here is the date.h header file where I'm calling parse_formatted_date from:
#ifndef DATE_H_
#define DATE_H_
// Define the structure date.
typedef struct {
int day;
int month;
int year;
} date;
// Parses a string 'formatted_date' representing a date
// in format DD-MM-YYYY, DD.MM.YYYY or DD/MM/YYYY
// into a structure date 'parsed_date'.
void parse_formatted_date(char * formatted_date, date * parsed_date) {
const int ret = sscanf(formatted_date, "%d-%d-%d",
&parsed_date->day,
&parsed_date->month,
&parsed_date->year);
//printf("Day: %d, Month: %d, Year: %d\n", d.day, d.month, d.year);
//return ret == 3;
}
#endif
At the moment, the errors I'm getting are:
main_Assignment4.c: In function ‘main’:
main_Assignment4.c:22: error: void value not ignored as it ought to be
Not sure what these errors mean or how to fix?
Thank you!
Modified answer
// Parses a string 'formatted_date' representing a date
// in format DD-MM-YYYY, DD.MM.YYYY or DD/MM/YYYY
// into a structure date 'parsed_date'.
void parse_formatted_date(char * formatted_date, date * parsed_date)
{
sprintf(formatted_date, "%d-%d-%d",
parsed_date->day,
parsed_date->month,
parsed_date->year);
}
int main(int arg, char *argv[]) {
/*
* Request a date from the user
* in format DD/MM/YYYY
*/
date d;
char input_date[20];
printf("Enter your date of birth in the form DD/MM/YYYY:");
fgets(input_date, 100, stdin);
sscanf(input_date,"%d/%d/%d", &d.day, &d.month, &d.year);
parse_formatted_date(input_date, &d);
printf("date: %s dd = %d, mm = %d, yy = %d\n", input_date, d.day, d.month, d.year);
return 0;
}
Implement a function that determines and prints out the current year, month and day. For example:
Today is 03/04/2014.
Code so far that I have:
#include <stdio.h>
#include <time.h>
int main ()
{
int days, weeks, months, years, option, rmd, currentyear, currentmonth;
int daysinjan, daysinfeb, daysinmarch;
time_t seconds;
seconds = time(NULL);
days = seconds/(60*60*24);
weeks = seconds/((60*60*24)*7);
rmd=seconds%31557600;
months = ((seconds/31557600) * 12)+(((float)rmd/31557600)*12);
years = days/(365.25);
currentyear = 1970 + years;
currentmonth = (((float)rmd/31557600)*12)+1;
printf("%ld/%ld", currentmonth,currentyear);
return 0;
}
Please do not mind all the useless stuff in the code, this question is part of a project and i simply used the code from my previous question to try and work with that code in order to solve this question. The problem i have is that i cannot print the current day of the month that it is, because of this i feel that i have gone about this question wrongly.
This uses standard library calls to do all the math for you.
From Here:
#include <time.h>
#include <stdio.h>
#define SIZE 256
int main (void)
{
char buffer[SIZE];
time_t curtime;
struct tm *loctime;
/* Get the current time. */
curtime = time (NULL);
/* Convert it to local time representation. */
loctime = localtime (&curtime);
/* Print out the date and time in the standard format. */
fputs (asctime (loctime), stdout);
/* Print it out in a nice format. */
strftime (buffer, SIZE, "Today is %A, %B %d.\n", loctime);
fputs (buffer, stdout);
strftime (buffer, SIZE, "The time is %I:%M %p.\n", loctime);
fputs (buffer, stdout);
return 0;
}
If you wanted to create this as a function to return a string, you could do it like this:
char * getTimeString (char *str)
{
//replace this comment with relevant code from above with (at least) two additional lines:
strcpy(str, buffer);
return str;
}
Call it like this:
int main(void)
{
char *timeStr;
timeStr = malloc(30);//sufficient length to accept values assigned in getTimeString()
printf("%s\n", getTimeString(timeStr);
free(timeStr);
return 0;
}
#include <time.h> // for time_t
#include <stdio.h> // for printf
int main () {
int days, weeks, months, years, option, rmd, currentyear, currentmonth;
int daysinjan, daysinfeb, daysinmarch;
time_t seconds;
seconds = time(NULL);
days = seconds/(60*60*24);
weeks = seconds/((60*60*24)*7);
rmd=seconds%31557600;
months = ((seconds/31557600) * 12)+(((float)rmd/31557600)*12);
years = days/(365.25);
currentyear = 1970 + years;
currentmonth = (((float)rmd/31557600)*12)+1;
printf("%ld/%ld", currentmonth,currentyear);
return 0;
}