如何将boost::date_time::date::day_of_week()转换为字符串类型

How to convert boost::date_time::date::day_of_week() to string type?

本文关键字:date 转换 字符串 week 类型 day boost time of      更新时间:2023-10-16

我想这样做。

ptime now = second_clock::local_time();
date today = now.date();
today.day_of_week();
string day = "Sat";
if(day == to_string(today.day_of_week()))
{
   //perform an action
}
else
{
   //perform another action
}

代码编译,但程序从不执行if块。我怎么能把day_of_week()转换成字符串?

我建议boost::lexical_cast<>:

std::string day = boost::lexical_cast<std::string>(today.day_of_week());

或简单的:

std::cout << today.day_of_week();

Live On c++ Shell

#include <boost/date_time/posix_time/posix_time_io.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/lexical_cast.hpp>
int main() {
    auto now = boost::posix_time::second_clock::local_time();
    auto today = now.date();
    std::string day = boost::lexical_cast<std::string>(today.day_of_week());
    std::cout << today.day_of_week();
}

打印

Fri