Reputation: 4595
Given this is a basic question, I imagine there might be duplicates, but I could not find any. I simply want to get the current iso_date ( like 20110503 ) from boost.
Any pointers ?
Upvotes: 8
Views: 15106
Reputation: 4479
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 to configure 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 using git clone https://gist.github.com/9410910.git datetime
. To build the program run these commands: cd datetime && cmake . && make && ./datetime
.
Here are my snippets: https://gist.github.com/kwk/9410910
I hope this is useful for somebody.
Upvotes: 11
Reputation: 62975
I assume you're looking for a Boost.Date_Time-based 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'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();
}
See Date Time Input/Output for more information on the available format flags.
Upvotes: 12