Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date in another Timezone: C++ on Linux

Is there any way of getting the date...preferably in YYYYMMDD format...in the Australia/Sydney timezone (not just GMT+11).....through C++ on Linux?

Thanks,

Roger

like image 420
Roger Moore Avatar asked Nov 09 '10 13:11

Roger Moore


People also ask

How do I change the UTC date in Linux?

To change the time zone in Linux systems use the sudo timedatectl set-timezone command followed by the long name of the time zone you want to set.

How do I change the timezone on Linux OS?

Select the Terminal program from your Linux programs, or press Ctrl + Alt + T on your keyboard. Enter the time zone menu command. Depending on your Linux distribution, this command will vary: Ubuntu and Mint - sudo dpkg-reconfigure tzdata followed by the admin/user password.

Which function changes date from one timezone to another?

setTimeZone() method to convert the date time to the given timezone.

How do I get a list of timezones in Linux?

We can use the date command to view the timezone. Simply type the Linux command date in the terminal and you will get the required output.


1 Answers

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

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

std::string tz = "Australia/Sydney";
setenv("TX", const_cast<char *>(tz.c_str()), 1);
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 changing the timezone information does not end well.

This Answer Gives you a way to do it using boost, which is definitely much easier.

like image 180
Petesh Avatar answered Oct 13 '22 20:10

Petesh