I would like to know how I can get the UTC time or any other timezone ( NOT just local time) in C++ Linux.
I would like to do something like: int Minutes = time.now(Minutes)
to get and store the year, month, day, hour, minute and second at that exact time.
How I can do so?
I will need to repeat this process many time; I want to know the newest and best way to do so.
You are looking for the gmtime
function in the time.h
library, which give you UTC time. Here's an example:
#include <stdio.h> /* printf */
#include <time.h> /* time_t, struct tm, time, gmtime */
int main ()
{
time_t rawtime;
struct tm * ptm;
// Get number of seconds since 00:00 UTC Jan, 1, 1970 and store in rawtime
time ( &rawtime );
// UTC struct tm
ptm = gmtime ( &rawtime );
// print current time in a formatted way
printf ("UTC time: %2d:%02d\n", ptm->tm_hour, ptm->tm_min);
return 0;
}
Look at these sources:
You can use system command in c++ if you want linux oriented solution
eg
#include <iostream>
#include <sstream> //for stringstream function to store date and time
using namespace std;
int main()
{
const char *date_now = "date -u"; //linux command to get UTC time is "date -u"
stringstream s;
s << system(date_now); //to store output of system("date_now") to s;
cout << s.str() << endl; //to print the string in s
return 0;
}
Check out "date --help" for more date and time related commands in linux terminal.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.