Skip to content

Instantly share code, notes, and snippets.

@magicianlib
Last active October 19, 2023 10:47
Show Gist options
  • Save magicianlib/238560679f9f8d730115be624c082e36 to your computer and use it in GitHub Desktop.
Save magicianlib/238560679f9f8d730115be624c082e36 to your computer and use it in GitHub Desktop.
C++ 日期格式化
#include <chrono>
#include <ctime>
#include <iostream>
#include <string>
/**
* date format to string
* https://cplusplus.com/reference/ctime/strftime/
*/
std::string datetime_format(std::time_t time, const std::string& format, std::size_t sz = 20) {
std::string datetime(sz, '\0');
std::strftime(&datetime[0], datetime.size(), format.data(), std::localtime(&time));
return datetime;
}
std::string curr_format(const std::string& format, std::size_t sz = 20) {
typedef std::chrono::system_clock Clock;
return datetime_format(Clock::to_time_t(Clock::now()), format, sz);
}
int main() {
typedef std::chrono::system_clock Clock;
std::time_t now{Clock::to_time_t(Clock::now())};
std::cout << curr_format("现在是 %F %T", 50).c_str() << '\n';
std::cout << datetime_format(now, "现在是 %F").c_str() << '\n';
std::cout << datetime_format(now, "现在是 %T").c_str() << '\n';
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment