How to get current UTC date in boost?

Given that this is the main question, I assume that there may be duplicates, but I could not find them. I just want to get the current iso_date (e.g. 20110503) from boost.

Any pointers?

+6
source share
2 answers

I assume you are looking for a Boost.Date_Time solution?

#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 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(); } 

For more information on the available format flags, see "Time In / Out" .

+11
source

To print the current date and time in UTC, you can use this code (save as 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; } 

Here's the CMake code for setting up your build (save as 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}) 

Put both files in a directory or clone my snippets with git clone https://gist.github.com/9410910.git datetime . To build the program, run the following commands: cd datetime && cmake . && make && ./datetime cd datetime && cmake . && make && ./datetime .

Here are my snippets: https://gist.github.com/kwk/9410910

Hope this is helpful to someone.

+6
source

Source: https://habr.com/ru/post/887155/


All Articles