【发布时间】:2012-01-10 17:39:15
【问题描述】:
如何获取当前日期 d/m/y。我需要它们有 3 个不同的变量而不是一个,例如 day=d; month=m; year=y;。
【问题讨论】:
-
@Fredrik,提问比研究简单。
如何获取当前日期 d/m/y。我需要它们有 3 个不同的变量而不是一个,例如 day=d; month=m; year=y;。
【问题讨论】:
对于 linux,您可以使用 'localtime' 函数。
#include <time.h>
time_t theTime = time(NULL);
struct tm *aTime = localtime(&theTime);
int day = aTime->tm_mday;
int month = aTime->tm_mon + 1; // Month is 0 - 11, add 1 to get a jan-dec 1-12 concept
int year = aTime->tm_year + 1900; // Year is # years since 1900
【讨论】:
这里是 chrono 方式 (C++0x) - 在 http://ideone.com/yFm9P
#include <chrono>
#include <ctime>
#include <iostream>
using namespace std;
typedef std::chrono::system_clock Clock;
int main()
{
auto now = Clock::now();
std::time_t now_c = Clock::to_time_t(now);
struct tm *parts = std::localtime(&now_c);
std::cout << 1900 + parts->tm_year << std::endl;
std::cout << 1 + parts->tm_mon << std::endl;
std::cout << parts->tm_mday << std::endl;
return 0;
}
【讨论】:
std::time_t 需要标头
<ctime>。它肯定会被<chrono> 收录。
【讨论】:
#include <ctime> #include <iostream> using namespace std; int main() { time_t t = time(0); // get time now struct tm * now = localtime( & t ); cout << (now->tm_year + 1900) << '-' << (now->tm_mon + 1) << '-' << now->tm_mday << endl; } 谢谢