如何在boost中获取当前的UTC日期?

时间:2011-05-03 00:33:33

标签: c++ date boost

鉴于这是一个基本问题,我想可能有重复,但我找不到。 我只想从boost获得当前的iso_date(如20110503)。

任何指针?

2 个答案:

答案 0 :(得分:11)

我假设您正在寻找基于Boost.Date_Time的解决方案?

#include <locale>
#include <string>
#include <iostream>
#include <sstream>
#include <boost/date_time/gregorian/gregorian.hpp>

std::string utc_date()
{
    namespace bg = boost::gregorian;

    static char const* const fmt = "%Y%m%d";
    std::ostringstream ss;
    // assumes std::cout's locale has been set appropriately for the entire app
    ss.imbue(std::locale(std::cout.getloc(), new bg::date_facet(fmt)));
    ss << bg::day_clock::universal_day();
    return ss.str();
}

有关可用格式标志的详细信息,请参阅Date Time Input/Output

答案 1 :(得分:7)

要以UTC格式打印当前日期和时间,您可以使用此代码(另存为datetime.cpp):

#include <iostream>

// Not sure if this function is really needed.
namespace boost { void throw_exception(std::exception const & e) {} }

// Includes
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/local_time_adjustor.hpp>
#include <boost/date_time/c_local_time_adjustor.hpp>

int main(int argc, char *argv[])
{
    // Code
    using boost::posix_time::ptime;
    using boost::posix_time::second_clock;
    using boost::posix_time::to_simple_string;
    using boost::gregorian::day_clock;

    ptime todayUtc(day_clock::universal_day(), second_clock::universal_time().time_of_day());
    std::cout << to_simple_string(todayUtc) << std::endl;

    // This outputs something like: 2014-Mar-07 12:56:55

    return 0;
}

以下是配置构建的CMake代码(另存为CMakeLists.txt):

cmake_minimum_required(VERSION 2.8.8)

project(datetime)

find_package(Boost COMPONENTS date_time REQUIRED)
include_directories(${Boost_INCLUDE_DIRS})

add_executable(datetime datetime.cpp)

target_link_libraries(datetime ${Boost_LIBRARIES})

将两个文件放在目录中或使用git clone https://gist.github.com/9410910.git datetime克隆我的代码段。要构建程序,请运行以下命令:cd datetime && cmake . && make && ./datetime

以下是我的摘要:https://gist.github.com/kwk/9410910

我希望这对某些人有用。