代码之家  ›  专栏  ›  技术社区  ›  Crystal

解析C++中的本地时间

  •  2
  • Crystal  · 技术社区  · 15 年前

    有没有一个简单的“初学者”方法来利用目前的时间使用 <ctime> 到日期对象

    int month
    int day
    int year
    

    因为它是成员变量?谢谢。

    2 回复  |  直到 13 年前
        1
  •  4
  •   bluish dmajkic    13 年前
    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 结构ints都是基于0的(0=jan,1=feb),您可以得到各种各样的日度量,日复一日( tm_mday (星期) tm_wday 和年( tm_yday )

        2
  •  2
  •   Sergey Kurenkov    15 年前

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

    #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;
    }
    
    推荐文章