tags:

views:

1138

answers:

6

Hi.. I need function in c++ that allows me to retrieve and store the system date. I have a class for storing dates.

+5  A: 

From time.h:

struct tm {
    int tm_sec;     /* seconds after the minute - [0,59] */
    int tm_min;     /* minutes after the hour - [0,59] */
    int tm_hour;    /* hours since midnight - [0,23] */
    int tm_mday;    /* day of the month - [1,31] */
    int tm_mon;     /* months since January - [0,11] */
    int tm_year;    /* years since 1900 */
    int tm_wday;    /* days since Sunday - [0,6] */
    int tm_yday;    /* days since January 1 - [0,365] */
    int tm_isdst;   /* daylight savings time flag */
};

time_t time(time_t * timer);
struct tm* gmtime(const time_t *timer);
struct tm* localtime(const time_t * timer);
Jason
+2  A: 

For C++ on Windows look at the Windows time functions, in particular GetSystemTime.

tvanfosson
+8  A: 

Dealing with dates and time is difficult, thats why people use libraries. I prefer boost::date_time.

boost::posix_time::ptime local_time = boost::posix_time::second_clock::local_time();
boost::gregorian::date d = local_time.date();

d is a current date in local time, which use computer timezone settings. To get UTC time you can use boost::posix_time::second_clock::universal_time().

Lazin
I also like to use the Boost libraries as opposed to strictly using ctime and the associated functions.
Nick Presta
+1  A: 

Just to add, GetSystemTime gives you UTC time, while to get the TimeZone adjusted time you need to use GetLocalTime.

One more difference between WinBase time function (through windows.h) compared to time.h functions is windows time functions are reliable till 1601, while time.h is only till 1900 onwards. I am not sure if that is some thing which you need to consider.

Adarsha
A: 

time()

But also see localtime and asctime for display

Joshua
A: 

Here's what I ended up using (nowtm is populated with current system time):

time_t rawtime=time(NULL);
tm* nowtm = gmtime(&rawtime);

where tm is defined:

struct tm {
    int tm_sec;     /* seconds after the minute - [0,59] */
    int tm_min;     /* minutes after the hour - [0,59] */
    int tm_hour;    /* hours since midnight - [0,23] */
    int tm_mday;    /* day of the month - [1,31] */
    int tm_mon;     /* months since January - [0,11] */
    int tm_year;    /* years since 1900 */
    int tm_wday;    /* days since Sunday - [0,6] */
    int tm_yday;    /* days since January 1 - [0,365] */
    int tm_isdst;   /* daylight savings time flag */
};
Alex B