I've been trying to figure this out for a while and figured I'd ask some experts:

For a school assignment, I need to create a datebook program. One of the classes is a DateAndTime class. One constructor on the class is supposed to take an unsigned integer and convert it to Date and Time objects (other classes in the project).

My plan was to originally take the seconds since epoch and convert it to time_t then to struct tm so I could read in the month, date, year, hour, minute, second. Turns out that's harder than I thought.

Can anyone point me in the right direction?

Thanks!

That's pretty simple. Include the <ctime> header, then use the function localtime. That does the converting process from time_t to a tm structure, and from there you can extract the data into your objects. If you need to go the other way (tm to time_t), you can use the mktime function.

I still need to get an int to a time_t though.

I still need to get an int to a time_t though.

Ha, guess it is really easy

time_t sec = (time_t)secondsSinceEpoch;

Thank you!

In most of C and C++ implementations the time() returns the elapsed time in seconds from the Unix epoch. However both C and C++ standards do not specify time_t type granularity and the day of epoch. Therefore all programs based on "time_t in seconds and time() returns seconds from ...1970" assumptions are not portable.

The only standard library function which returns real time units value is difftime:

#include <time.h>
double difftime(time_t time1, time_t time0);
/* returns t1 - t0 in seconds as double */

Now it's not so hard to build a portable scheme to convert time_t values to seconds, to get current implementation time() epoch at run-time, save and restore user-defined type values of time stamps and so on (using time, mktime and difftime library functions).

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.