سؤال
هل هناك طريقة سهلة "المبتدئين" لأخذ الوقت الحالي <ctime>
إلى كائن تاريخ لديه
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
البنية ints كلها قائمة على 0 (0 = يناير ، 1 = فبراير) ويمكنك الحصول على تدابير مختلفة اليوم ، اليوم في الشهر (tm_mday
)، أسبوع (tm_wday
) والسنة (tm_yday
).
نصائح أخرى
إذا كان هناك localtime_r ، فيجب عليك استخدامه localtime_r بدلاً من المحلية لأن هذا هو الإصدار Reenrant من 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;
}
لا تنتمي إلى StackOverflow