parse localtime in c++
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;
}
精彩评论