wordpress建教学网站,外贸公司取名字大全集,漂亮的网站单页,wordpress自动内外网在C中#xff0c;你可以使用标准库中的 chrono 和 iomanip 头文件来获取当前时间并将其格式化为字符串。以下是一个简单的示例#xff0c;展示了如何获取当前时间并将其格式化为一个可读的字符串#xff08;例如#xff1a;YYYY-MM-DD HH:MM:SS#xff09…在C中你可以使用标准库中的 chrono 和 iomanip 头文件来获取当前时间并将其格式化为字符串。以下是一个简单的示例展示了如何获取当前时间并将其格式化为一个可读的字符串例如YYYY-MM-DD HH:MM:SS。
#include iostream
#include iomanip
#include sstream
#include ctime
#include chronostd::string getCurrentTimeString() {// 获取当前时间点auto now std::chrono::system_clock::now();// 将时间点转换为 time_t 类型自1970年1月1日以来的秒数std::time_t now_time_t std::chrono::system_clock::to_time_t(now);// 将 time_t 转换为 tm 结构std::tm* now_tm std::localtime(now_time_t);// 使用 std::ostringstream 将 tm 结构转换为字符串std::ostringstream oss;oss std::put_time(now_tm, %Y-%m-%d %H:%M:%S);return oss.str();
}int main() {std::string currentTime getCurrentTimeString();std::cout Current time: currentTime std::endl;return 0;
}解释
获取当前时间点使用 std::chrono::system_clock::now() 获取当前的时间点。转换为 time_t 类型使用 std::chrono::system_clock::to_time_t() 将时间点转换为 time_t 类型它表示自1970年1月1日以来的秒数。转换为 tm 结构使用 std::localtime() 将 time_t 类型转换为 tm 结构这个结构包含了详细的日期和时间信息。格式化为字符串使用 std::ostringstream 和 std::put_time() 将 tm 结构格式化为一个字符串。%Y-%m-%d %H:%M:%S 是格式字符串其中 %Y 表示四位数的年份%m 表示两位数的月份%d 表示两位数的日期%H 表示两位数的小时24小时制%M 表示两位数的分钟%S 表示两位数的秒。
运行这个程序将输出当前时间格式为 YYYY-MM-DD HH:MM:SS。