In c++, I would like to get the number of seconds from between the current time and January 1, 2000. The problem that I'm having is assigning one time struct with the current time, and another with other one. When I use difftime(), it just returns 0. There is something that I'm obviously missing.

#include <stdio.h>
#include <time.h>
#include <iostream>

int main ()
{
	time_t oldTime;

	struct tm oldTimePtr;
	oldTimePtr.tm_year	= 2000 - 1900;
	oldTimePtr.tm_mday	= 1;
	oldTimePtr.tm_min	= 0;
	oldTimePtr.tm_mon	= 0;
	oldTimePtr.tm_sec	= 0;
	oldTimePtr.tm_wday	= 0;
	
	oldTime = mktime( &oldTimePtr );

	//current time
	time_t currentTime = time(0);
	struct tm *currentTimeStruct = localtime( &currentTime );


	std::cout << difftime( currentTime, oldTime );

	std::cin.get();
  
  return 0;
}

Recommended Answers

All 6 Replies

Did you try outputting the two values (oldTime/currentTime) to see if they hold data that looks correct?

They both come out to -1. When I use ctime() I get an access writing violation. I am so confused on how this works.

You got -1 because mktime() also considers the hours, minutes and seconds fields of the tm structure. Just use memset() to initialize the structure to all 0 then fill in the year month and day

Also -- difftime() takes two time_t objects, not pointers to two struct tm objects.

#include <iostream>
#include <iomanip>
#include <ctime>
using std::cout;
using std::cin;

int main()
{
    struct tm oldTimePtr;
memset(&oldTimePtr,0,sizeof(struct tm));
oldTimePtr.tm_year	= 2000 - 1900;
oldTimePtr.tm_mday	= 1;
time_t oldTime = mktime(&oldTimePtr);
time_t now = time(0);
cout << std::fixed << difftime(now, oldTime) << '\n';
cin.get();

}

This is great, thank you. I knew it was something simple.

Better yet, just add oldTimePtr.tm_hour = 0; since that's the only value you're missing. It's more explicit.

but how about the minute and second? memset() does it all in one bang, faster, and less typing :)

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.