目前我正在运行以下代码
int main() {
while(1)
{
time_t current = time(NULL);
cout << ctime(¤t)<< endl;
}
}
我的输出如下所示:
2017 年 1 月 15 日星期日 00:03:25
2017 年 1 月 15 日星期日 00:03:25
因为小时是 00,分钟是 03,秒是 25。我想将 00 存储在某个整数变量中,比如说 int hrs,将 03 存储在变量 int min 和 25 位于变量 int sec 中。怎么做?
最佳答案
您想要的函数是本地时间
。
该函数获取time_t
的地址并返回一个指向struct tm
的指针,其中包含 segmentation 为年、月、日、小时的日期和时间,分钟和秒。
来自man page :
struct tm *localtime(const time_t *timep);
The
localtime()
function converts the calendar timetimep
to broken-down time representation, expressed relative to the user's specified timezone. The function acts as if it calledtzset(3
) and sets the external variablestzname
with information about the current timezone, timezone with the difference between Coordinated Universal Time (UTC) and local standard time in seconds, and daylight to a nonzero value if daylight savings time rules apply during some part of the year. The return value points to a statically allocatedstruct
which might be overwritten by subsequent calls to any of the date and time functions.
struct tm的定义如下:
struct tm {
int tm_sec; /* seconds */
int tm_min; /* minutes */
int tm_hour; /* hours */
int tm_mday; /* day of the month */
int tm_mon; /* month */
int tm_year; /* year */
int tm_wday; /* day of the week */
int tm_yday; /* day in the year */
int tm_isdst; /* daylight saving time */
};
关于c++ - 将日期成员存储在不同的变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41650465/