how to subtract two dates to find no of days .

Recommended Answers

All 5 Replies

i think that you can use

enum

it is as

structure

but enum list the elements by index as array .. for example

enum days_of_the_week ={sat,sun,mon,tue,wed,thu,fri };

there for .. sat has the value 0 and sun = 1 and mon = 2 and so on ..
so if u say mon - sat
the compiler wil supstract the values only ... ther for u will get 2 .

enum days_of_the_week ={sat,sun,mon,tue,wed,thu,fri };

there for .. sat has the value 0 and sun = 1 and mon = 2 and so on ..
so if u say mon - sat
the compiler wil supstract the values only ... ther for u will get 2 .

This is one way.

[b]#include[/b] <iostream>
[b]#include[/b] <ctime> 
 
[b]int[/b] [b]main[/b]() 
{
[b]   struct[/b] std::tm a = {0,0,0,24,5,104}; /* June 24, 2004 */
[b]   struct[/b] std::tm b = {0,0,0,5,6,104}; /* July 5, 2004 */
   std::time_t x = std::[b]mktime[/b](&a);
   std::time_t y = std::[b]mktime[/b](&b);
[b]   if [/b]( x != (std::time_t)(-1) && y != (std::time_t)(-1) )
   {
	 [b]double[/b] difference = std::[b]difftime[/b](y, x) / (60 * 60 * 24);
	 std::[b]cout[/b] << std::ctime(&x);
	 std::[b]cout[/b] << std::ctime(&y);
	 std::[b]cout[/b] << "difference = " << difference << " days" << std::[b]endl[/b];
   }
[b]   return[/b] 0; 
}
 
/* my output
Thu Jun 24 01:00:00 2004
Mon Jul 05 01:00:00 2004
difference = 11 days
*/

you are only 8 years too late with your post, and that is a horribly complex program for just subtracting two dates.

Not to mention it wouldn't pass code review in any development house I've worked with (assuming it compiled). The code itself is brittle and the solution is clearly written by someone who hasn't done much date and time programming.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.