Compare two times in C
Use difftime(time1, time0)
from time.h
to get the difference between two times. This calculates time1 - time0
and returns a double
representing the difference in seconds. If it's positive, then time1
is later than time0
; if negative, time0
is later; if 0, they're the same.
How to print time difference in accuracy of milliseconds and nanoseconds from C in Linux?
Read first the time(7) man page.
Then, you can use clock_gettime(2) syscall (you may need to link -lrt
to get it).
So you could try
struct timespec tstart={0,0}, tend={0,0};
clock_gettime(CLOCK_MONOTONIC, &tstart);
some_long_computation();
clock_gettime(CLOCK_MONOTONIC, &tend);
printf("some_long_computation took about %.5f seconds\n",
((double)tend.tv_sec + 1.0e-9*tend.tv_nsec) -
((double)tstart.tv_sec + 1.0e-9*tstart.tv_nsec));
Don't expect the hardware timers to have a nanosecond accuracy, even if they give a nanosecond resolution. And don't try to measure time durations less than several milliseconds: the hardware is not faithful enough. You may also want to use clock_getres
to query the resolution of some clock.
Calculating time difference in C (days, hours, minutes, seconds)
Given that this is a poor way to calculate time difference, there are two problems:
- scanf cannot separate integers
- hour difference is wrong
Try this:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int day1, hour1, min1, sec1, day2, hour2, min2, sec2, totalTime;
printf("Enter input:");
scanf("%d,%d,%d,%d,%d,%d,%d,%d", &day1, &hour1, &min1, &sec1, &day2, &hour2, &min2, &sec2);
totalTime = (day2 - day1) * 86400 + (hour2 - hour1) * 3600 + (min2 - min1) * 60 + (sec2 - sec1);
printf("D: %d\n", totalTime / 86400);
totalTime = totalTime % 86400;
printf("H: %d\n", totalTime / 3600);
totalTime = totalTime % 3600;
printf("M: %d\n", totalTime / 60);
totalTime = totalTime % 60;
printf("S: %d\n", totalTime);
return 0;
}
A better way to calculate time difference could be by using difftime function
Time difference between system time and user inpuit time in C Programming
current_time
is of type time_t
which is basically an integer and does not have member variable like struct
s.
So you can't do like current_time.hour
.
time_t
stores the total number seconds from the UNIX epoch.
The user given time in your program does not include details like year, month, etc and has just hour, minute and second information. The time_t
that you get via time()
has the total number number of seconds from the UNIX epoch.
So, you may want to use just the hour, minute, second information like
time_t t=time(NULL);
struct tm *c=localtime(&t);
int seconds2 = c->tm_hour*60*60 + c->tm_min*60 + c->tm_sec;
struct tm
is a structure to store components of the calendar time and localtime()
localtime converts the calendar time into local time and returns a pointer to a struct tm
.
tm_hour
, tm_min
and tm_sec
are members of struct tm
denoting th hour, minute and second respectively.
Note that the hour in tm_hour
is in 24 hours format. If you want a 12 hour version, use tm_hour%12
.
Get Time Difference without if else statement
Use (some sort of) timestamps, by turning your hours and minutes variables into one, e.g:
stime = shours * 60 + sminutes;
etime = ehours * 60 + eminutes;
then calculate de difference of that
totime = etime - stime;
then convert that back into hours and minutes
tominutes = totime % 60;
tohours = (totime - tominutes) / 60;
(integer division will take care of rounding down)
Not the most elaborated solution, but I guess you're looking for an beginners-friendly solution
Edit
speaking of beginner-friendly: the % is the modulus operator that returns the remainder of a division. So when you divide 119 by 60 it returns 59. And yes, you could also just get the hours from dividing totime by 60 and let the integer division do the job, but it's nicer (read: clearer to read what's going on) when you divide (totime - tominutes) because it's like the missing part to the line with the modulus
Calculating difference between two date-times in C++
You use the conversion specifier%b
to get the month but it should be %m
:
ssBuffer >> get_time(&tm, "%Y-%m-%d:%H:%M:%S");
%b
- parses the month name, either full or abbreviated, e.g. Oct (non-numeric)%m
- parses the month as a decimal number (range [01,12]), leading zeroes permitted but not required
The year and month are correct. 121 is the number of years since 1900 and 9 is the month, zero-based [0,11], which is what's specified for std::tm
.
Related Topics
What Use Are Const Pointers (As Opposed to Pointers to Const Objects)
Templates: Template Function Not Playing Well with Class's Template Member Function
Is There a C++11 Syntax File for Vim
Exception Running Boost Asio Ssl Example
Friend Declaration Declares a Non-Template Function
How to Forward Declare a Template Class in Namespace Std
How to Use C++ Std::Ostream with Printf-Like Formatting
Do Negative Numbers Return False in C/C++
Is There a Downside to Declaring Variables with Auto in C++
Maximum Number of Parameters in Function Declaration
How to Find Longest Common Substring Using C++
C++ Most Efficient Way to Convert String to Int (Faster Than Atoi)