时间转字符串有两种方法
#include
#include
std::string getCurrentTime() {
boost::posix_time::ptime currentTime = boost::posix_time::microsec_clock::local_time();
std::string formattedTime = boost::posix_time::to_iso_extended_string(currentTime);
return formattedTime;
}
int main() {
std::string currentTime = getCurrentTime();
std::cout << "Current time: " << currentTime << std::endl;
return 0;
}
格式化为指定格式字符串
#include
#include
#include
std::string formatTime(const boost::posix_time::ptime& time, const std::string& format) {
std::ostringstream oss;
boost::posix_time::time_facet* facet = new boost::posix_time::time_facet();
facet->format(format.c_str());
oss.imbue(std::locale(std::cout.getloc(), facet));
oss << time;
return oss.str();
}
int main() {
boost::posix_time::ptime currentTime = boost::posix_time::microsec_clock::local_time();
std::string formattedTime = formatTime(currentTime, "%Y-%m-%d %H:%M:%S.%f");
std::cout << "Formatted time: " << formattedTime << std::endl;
return 0;
}
#include
#include
int main() {
std::string formattedString = "2021-09-30 10:30:00";
boost::posix_time::ptime time = boost::posix_time::time_from_string(formattedString);
std::cout << "Converted time: " << time << std::endl;
return 0;
}
指定格式字符串转为时间
#include
#include
#include
#include
#include
int main() {
std::string formattedString = "2021-09-30 10:30:00";
std::istringstream iss(formattedString);
iss.imbue(std::locale(iss.getloc(), new boost::posix_time::time_input_facet("%Y-%m-%d %H:%M:%S")));
boost::posix_time::ptime time;
iss >> boost::posix_time::time_input(time);
std::cout << "Converted time: " << time << std::endl;
return 0;
}