C'è un modo per ottenere la data ... preferibilmente nel formato AAAAMMGG ... nel fuso orario Australia/Sydney (non solo GMT + 11) ..... tramite C++ su Linux?Data in un altro fuso orario: C++ su Linux
Grazie,
Roger
C'è un modo per ottenere la data ... preferibilmente nel formato AAAAMMGG ... nel fuso orario Australia/Sydney (non solo GMT + 11) ..... tramite C++ su Linux?Data in un altro fuso orario: C++ su Linux
Grazie,
Roger
Sì, ma è sufficiente utilizzare i meccanismi della libreria C standard.
impostare il fuso orario desiderato nell'ambiente creando una stringa:
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;
Il problema è che questo codice non è thread safe - filetti multipli cambiando le informazioni fuso orario non finisce bene.
This Answer Offre un modo per farlo utilizzando boost, che è decisamente molto più semplice.
Utilizzando Boost.DateTime (Attenzione: non testato, solo a scopo illustrativo)
// 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;
See:
risposta nuova per vecchia domanda:
Usando questo cross platform, open source C++11/C++14 timezone library si può scrivere:
#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';
}
Quale appena uscita per me:
20150824
E 'sicuro thread. È aggiornato come la copia dello IANA timezone database che hai appena scaricato. E se la data capita di non essere "adesso", userà correttamente i dati storici dal database IANA.