有一个简单的“初学者”的方式使用<ctime>到具有

Date对象采取的当前时间
int month
int day
int year

为它的成员变量?感谢。

有帮助吗?

解决方案

time_t tt = time(NULL); // get current time as time_t
struct tm* t = localtime(&tt) // convert t_time to a struct tm
cout << "Month "  << t->tm_mon 
     << ", Day "  << t->tm_mday
     << ", Year " << t->tm_year
     << endl

tm结构整数都从0(0 =月,1 = 2月),你可以得到各种一日措施,天月(tm_mday),周(tm_wday)和年份(tm_yday)。

其他提示

如果有则localtime_r,那么你应该使用则localtime_r ,而不是本地时间,因为这是本地时间的可重入版本。

#include <ctime>
#include <iostream>

int main()
{
    time_t tt = time(NULL); // get current time as time_t
    tm  tm_buf;
    tm* t = localtime_r(&tt, &tm_buf); // convert t_time to a struct tm

    std::cout << "Month "  << t->tm_mon
              << ", Day "  << t->tm_mday
              << ", Year " << t->tm_year
              << std::endl;
    return 0;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top