简体   繁体   中英

How to split the date and time in C++?

I'm trying to make a program wherein the user will input his/her birthday and the program will compute how many days, months, years, hours and minutes they've lived.

I've searched Google and I see there's a way to split the date into three to four parts.

I've copied this code and it seems to be working. It's just that I don't understand it. All the forums I've read don't help much either. Can anyone explain it to me?

time_t t = time(NULL);
tm* timePtr = localtime(&t);

cout << "seconds= " << timePtr->tm_sec << endl;
cout << "minutes = " << timePtr->tm_min << endl;
cout << "hours = " << timePtr->tm_hour << endl;
cout << "day of month = " << timePtr->tm_mday << endl;
cout << "month of year = " << timePtr->tm_mon << endl;
cout << "year = " << timePtr->tm_year + 1900 << endl;
cout << "weekday = " << timePtr->tm_wday << endl;
cout << "day of year = " << timePtr->tm_yday << endl;
cout << "daylight savings = " << timePtr->tm_isdst << endl;

This is not standard C++ code. This is (also) POSIX code.

(The recent C++11 standard gives you <chrono> but few compilers implement it; on Linux you'll need GCC 4.6 or 4.7; there is also <ctime> )

See this answer to a question very related to yours.

As for time , gettimeofday , localtime , strftime they have well written reference documentation in the manual page. What don't you understand?

(follow the links I gave you and read the linked pages carefully).

In most computing environments, dates and times are a unified concept. The C runtime library (hence also C++) provides the type time_t which measures time (and dates) as the number of seconds since 1970-01-01T00:00:00 UTC.

The localtime() function takes a time_t and converts that into the calendar-like fields which humans are accustomed to, according to the local timezone (which is obtained from the computer—the timezone can also be specified specifically). There is another very similar call, gmtime() which does not consider the local timezone, but always uses the UTC timezone, formerly called GMT.

To do what you want, accept from the user their birth date, birth time, and timezone, and convert that into a time_t . Then subtract that from the current time() value. The difference is the number of seconds they have been alive. To be friendly, use gmtime() to convert that to years, months, days, hours, minutes, and seconds.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM