开发者

parse localtime in c++

开发者 https://www.devze.com 2022-12-26 14:30 出处:网络
Is there an easy \"beginner\" way to take the current time using <ctime> to a Date obj开发者_开发知识库ect that has

Is there an easy "beginner" way to take the current time using <ctime> to a Date obj开发者_开发知识库ect that has

int month
int day
int year

for it's member variables? Thanks.


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

The tm struct ints are all 0-based (0 = Jan, 1 = Feb) and you can get various day measures, day in month (tm_mday), week (tm_wday) and year(tm_yday).


If there is localtime_r then you should use localtime_r rather than localtime since this is the reentrant version of 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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号