[编程语言][C++]时间处理

#include 
#include 
#include 
#include 
#include 

inline std::string ToString(const std::chrono::system_clock::time_point &tp)
{
	std::time_t time = std::chrono::system_clock::to_time_t(tp);

	// std::string ts = std::ctime(&t);
	// ts.resize(ts.size() - 1);
	// return ts;

	// std::tm *tm = std::gmtime(&time);
	std::tm *tm = std::localtime(&time);
	std::stringstream sstream;
	sstream << std::put_time(tm, "%F %T");

	return sstream.str();
}

inline std::chrono::system_clock::time_point MakeTimePoint(
	int year, int month, int day,
	int hour = 0, int minute = 0, int second = 0)
{
	struct std::tm t;
	t.tm_year = year - 1900;
	t.tm_mon = month - 1;
	t.tm_mday = day;
	t.tm_hour = hour;
	t.tm_min = minute;
	t.tm_sec = second;
	t.tm_isdst = -1;

	std::time_t tt = std::mktime(&t);
	if (tt == -1)
	{
		std::stringstream sstream;
		sstream << "Invalid system time(std::tm.tm_isdst = ";
		sstream << t.tm_isdst;
		sstream << ")";
		throw sstream.str();
	}

	return std::chrono::system_clock::from_time_t(tt);
}

int main()
{
	try
	{
		auto tp1 = MakeTimePoint(2010, 1, 1);
		std::cout << ToString(tp1) << std::endl;

		auto tp2 = MakeTimePoint(2011, 5, 23, 13, 44);
		std::cout << ToString(tp2) << std::endl;

		auto now = std::chrono::system_clock::now();
		std::cout << ToString(now) << std::endl;
	}
	catch (std::string str)
	{
		std::cerr << str << std::endl;
	}
}

你可能感兴趣的:(c++)