C ++ function that returns system date

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

+1


source to share


7 replies


Working with dates and times is difficult, so 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 the current local time date that uses the computer's time zone settings. To get UTC time you can use boost :: posix_time :: second_clock :: universal_time ().

+7


source


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);

      

+5


source


For C ++ on Windows, pay attention to the timing , specifically GetSystemTime .

+2


source


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

Another difference between the WinBase time function (via windows.h) versus the time.h functions is that the time functions in windows are reliable up to 1601, and time.h is only reliable until 1900. I'm not sure if this is what you need to consider.

+2


source


Time()

But also see localtime and asctime for display

0


source


Here's what I ended up using ( nowtm

populated with the 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 */
};

      

0


source


I wrote a fairly similar answer a few minutes ago. You can use chrono in C ++ 11. http://en.cppreference.com/w/cpp/chrono/time_point

0


source







All Articles