【问题标题】:parse localtime in c++在 C++ 中解析本地时间
【发布时间】:2011-02-07 18:53:30
【问题描述】:

是否有一种简单的“初学者”方法可以使用 <ctime> 将当前时间转换为具有的 Date 对象

int month
int day
int year

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

【问题讨论】:

标签: c++ ctime


【解决方案1】:
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 struct int 都是从 0 开始的(0 = 1 月,1 = 2 月),您可以获得各种日度量值、月中日(tm_mday)、周(tm_wday)和年(@ 987654325@)。

【讨论】:

    【解决方案2】:

    如果有 localtime_r,那么您应该使用 localtime_r 而不是 localtime,因为这是 localtime 的可重入版本。

    #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;
    }
    

    【讨论】:

      猜你喜欢
      • 2020-02-05
      • 1970-01-01
      • 2014-06-11
      • 2019-02-12
      • 1970-01-01
      • 2021-02-27
      • 1970-01-01
      • 1970-01-01
      • 2017-05-27
      相关资源
      最近更新 更多