Date in a different time zone: C ++ on Linux

Is there a way to get the date ... preferably in the format YYYYMMDD ... in the time zone of Australia / Sydney (and not just GMT + 11) ..... via C ++ on Linux?

Thank,

Roger

+5
source share
3 answers

Yes, but you just use the standard c library mechanisms.

set the desired time zone in the environment by creating a line:

std::string tz = "TZ=Australia/Sydney";
putenv(const_cast<char *>(tz.c_str()));
tzset(); // Initialize timezone data
time_t aTime = time(NULL); // get the time - this is GMT based.
struct tm retTime;
localtime_r(aTime, &retTime); // Convert time into current timezone.
char destString[1024];
strftime(destString, 1023, "%Y%m%d %Z", &retTime); // Format the output in the local time.
std::cout << destString << std::endl;

The problem is that this code is not thread safe - multiple threads that change time zone information do not end well.

This answer gives you the opportunity to do this with boost, which is certainly much simpler.

+4
source

Boost.DateTime(: , )

// Load the timezone database
tz_database db;
// TODO: Adjust this path to your environment
db.load_from_file("./boost/libs/date_time/data/date_time_zonespec.csv"); 

// Get the Sydney timezone
time_zone_ptr sydney_zone = db.time_zone_from_region("Australia/Sydney");

// Current date/time in Sydney
local_date_time sydney_time = local_sec_clock::local_time(sydney_zone);

// Format sydney_time in desired format
std::ostringstream formatter;
formatter.imbue(std::locale(), new local_time_facet("%Y%m%d"));
formatter << sydney_time;

:

+1

:

-, ++ 11/++ 14, :

#include "tz.h"
#include <iostream>

int
main()
{
    using namespace std::chrono;
    using namespace std;
    using namespace date;
    auto ymd = make_zoned("Australia/Sydney", system_clock::now());
    cout << format("%Y%m%d", ymd) << '\n';
}

:

20150824

. , IANA, . "", IANA.

+1
source

All Articles