#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
Related
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
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;
}
I need to validate a date-time value for "YYYYMMDDHHMMSSmmmmmm" format. Actually what I am hoping is I need to find out a already tested working C code to validate a date time value for above format.
Further, I have a date-time value like 201304011031000000. I need a function to verify whether this is a valid date or not.[isdatetime()]
Below are the each parts of formats.
YYYY : Year
MM : Month
DD : Day
HH : hour
MM : Minutes
SS : seconds
mmmmmm: micro-seconds
If you're on a POSIX system, this looks like something that should be handled with strptime(), but the 'milliseconds' (or microseconds) part is not handled by strptime() or any other standard conversion function I know of.
Assuming the question is asking for microseconds, you could use a variation on the theme provided by:
#include <stdio.h>
#include <string.h>
#include <time.h>
int main(void)
{
const char datetime[] = "20130417221633012345"; // YYYYMMDDHHMMSSFFFFFF
struct tm time_val;
unsigned microsecs;
const char *end = strptime(datetime, "%Y%m%d%H%M%S", &time_val);
if (end != 0)
{
int nbytes;
if (strlen(end) == 6 && sscanf(end, "%6u%n", µsecs, &nbytes) == 1 &&
nbytes == 6)
{
char buffer[32];
strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", &time_val);
printf("%s = %s.%.6u\n", datetime, buffer, microsecs);
}
}
return 0;
}
Revised requirement
#include <stdio.h>
#include <string.h>
#include <time.h>
int isdatetime(const char *datetime)
{
// datetime format is YYYYMMDDHHMMSSFFFFFF
struct tm time_val;
unsigned microsecs;
int nbytes;
const char *end = strptime(datetime, "%Y%m%d%H%M%S", &time_val);
if (end != 0 && strlen(end) == 6 &&
sscanf(end, "%6u%n", µsecs, &nbytes) == 1 && nbytes == 6)
return 1; // Valid
return 0; // Invalid
}
You can use regex.h for windows or for linux.
"YYYYMMDDHHMMSSMSSSSS" is something like: (\d{4}[0,1][0,9]\d{})... you can find your specific format here, it depends wether you enable 24 or 12 clock etc.
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.
I am trying to get Saturday's date of the week in Linux C. Using the function time and localtime, I got today's date and time details. How to proceed further to get Saturday's date?
#include <time.h>
#include <stdio.h>
#include <string.h>
int main()
{
char date[20];
struct tm *curr_tm = NULL;
time_t curr_time;
curr_time = time(NULL);
curr_tm = localtime(&curr_time);
curr_tm->tm_wday = 6;
//Refers to saturday.
printf("new date %d\t%d\t%d\n", curr_tm->tm_mday, curr_tm->tm_mon, curr_tm->tm_year+1900);
return 1;
}
How should I proceed with this?
struct tm orig;
// ...
// struct tm correctly set with everything within range.
orig.tm_mday += 6 - orig.tm_wday;
mktime(&orig);
tm_mday is the number of days since Sunday. Thus, 6 minus that is the number of days until Saturday (if today is Saturday it does nothing). This puts the structure out of range, which mktime fixes.
EDIT:
curr_time->tm_mday += 6 - curr_time->tm_wday;
mktime(curr_time);
Based on your code, the following will get you the next Saturday (today if it's Saturday).
#include <time.h>
#include <stdio.h>
#include <string.h>
int main() {
char date[20];
struct tm *curr_tm = NULL;
time_t curr_time;
curr_time = time(NULL);
curr_tm = localtime(&curr_time);
// Add the difference between todays day of week and Saturday, then re-make.
curr_tm->tm_mday += 6 - curr_tm->tm_wday;
mktime (curr_tm);
printf("new date %d\t%d\t%d\n",
curr_tm->tm_mday, curr_tm->tm_mon+1, curr_tm->tm_year+1900);
return 1;
}
You can replace the curr_tm->tm_mday += 6 - curr_tm->tm_wday; line with:
curr_tm->tm_mday += (curr_tm->tm_wday == 6) ? 7 : 6 - curr_tm->tm_wday;
to get next Saturday even if today is Saturday.