The date format is dd-mm-yyyy (it's the format here in Portugal), and the hour is hh:mm. My code is this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
struct DateTime {
int day, month, year, hour, minute;
};
// Function to convert date and time to minutes since midnight
int minutes_since_midnight(struct DateTime dt) {
return dt.hour * 60 + dt.minute;
}
// Function to calculate time difference
int calculate_time_difference(char date_in[], char time_in[], char date_out[], char time_out[]) {
struct DateTime dt1, dt2;
sscanf(date_in, "%d-%d-%d", &dt1.day, &dt1.month, &dt1.year);
sscanf(time_in, "%d:%d", &dt1.hour, &dt1.minute);
sscanf(date_out, "%d-%d-%d", &dt2.day, &dt2.month, &dt2.year);
sscanf(time_out, "%d:%d", &dt2.hour, &dt2.minute);
// Convert date and time to minutes since midnight
int minutes1 = minutes_since_midnight(dt1);
int minutes2 = minutes_since_midnight(dt2);
// Calculate total difference in minutes
int time_difference = abs(minutes2 - minutes1);
// Calculate day difference in minutes
int day_difference = dt2.day - dt1.day;
// If the date of departure is before the date of arrival, adjust the day difference
if (day_difference < 0) {
// Add a full day of minutes
day_difference += 1;
// Add the remaining hours of the departure day
time_difference += (24 - dt1.hour) * 60 + (60 - dt1.minute);
// Add the hours of the arrival day
time_difference += dt2.hour * 60 + dt2.minute;
} else {
// If the date of departure is after the date of arrival, just add the remaining minutes
time_difference += day_difference * 24 * 60;
}
return time_difference;
}
int main() {
int time_diff = calculate_time_difference("01-01-2024", "19:05", "02-01-2024", "9:05");
printf("Time difference->%i\n", time_diff);
return 0;
}
As you can see from the example in main, in the case where input 1 = "01-01-2024", "19:05" and input 2 = "02-01-2024", "9:05" the time difference in minutes should be 840 (14 hours * 60 minutes). The code when I run it says: Time difference->2040. How can I fix this?
Ignore leap years for this example.
Assuming no date comes before Jan 1, 1970 (standard epoch time). This should suffice. And if you do have pre-1970 dates, change the
int year = 1970statement below to have an initial value of1.The code below basically counts up the number of seconds from 1/1/1970 at midnight accounting for leap years as it goes.
Below assumes a basic understanding that:
DateTimestruct will never have negative numbers, months less than 1 or greater than 12. Hours are assumed to be between 0-23 (military time). Minutes are a value between 0-59.