如何在 c++ 中获取当前日期

How can I get current date in c++?

本文关键字:获取 当前日期 c++      更新时间:2023-10-16

我没有找到任何给出唯一日期的解决方案。我找到了解决方案,但一切都很复杂,我们必须解析数组并将日期与时间分开

尝试这样做

#include <iostream>
#include <iomanip>
#include <ctime>
int main()
{
    auto t = std::time(nullptr);
    auto tm = *std::localtime(&t);
    std::cout << std::put_time(&tm, "%d-%m-%Y %H-%M-%S") << std::endl;
}

如果你运行以下代码,那么今天你会发现当前日期采用以下格式。

15-04-14

#include<iostream>
#include<ctime>
using namespace std;
int main()
{
	char c[9];
	_strdate_s(c);
	cout<<c<<endl;
	return 0;
}

ideone code

#include <iostream>
#include <ctime>
using namespace std;
int main() 
{
    time_t now = time(0);
   tm *ltm = localtime(&now);
   cout << "Year: "<< 1900 + ltm->tm_year << endl;
   cout << "Month: "<< 1 + ltm->tm_mon<< endl;
   cout << "Day: "<<  ltm->tm_mday << endl;
}