user8305079
user8305079

Reputation:

Conversion of times in C++

This is what I am trying to do:

  1. Get the local time (from the system);
  2. Convert that time to the UTC format and associate it with some member variable of current object.
  3. Later on, given the timezone of the user, I wish to convert it into the correct local time and display it to the user.

Looking up few things on SO and CppReference, I could come up with the following snippet:

#include <iostream>
#include <iomanip>
#include <ctime>
#include <string>

using namespace std;

int main()
{
    time_t lt = std::time(0);
    //time(0) gives current time, but LTime shows the UTC time (not local time)
    string LTime = std::ctime(&lt); //localtime() gives error
    cout<<LTime;

    //timestamp = mktime(&tm) - timezone;
    //time_t timestamp = mktime(&tm) - _timezone;
    //std::cout << "timestamp: " << std::put_time(timestamp, "%c %Z") << '\n';

    return 0;
}
  1. The example on cppreference.com illustrates how the value can be printed using put_time(); but how to store it in a variable?
  2. How to convert the UTC time format to current timezone (given some timezone as the input)? I tried using the commented code above as per this link but it does not take any parameter.

Upvotes: 1

Views: 2426

Answers (1)

Hariom Singh
Hariom Singh

Reputation: 3632

You can use local time get the local time and gmt time for UTC You can set the Time zone using the list Time zone wiki

#include <iostream>
#include <iomanip>
#include <ctime>
int main()
{
    std::time_t result = std::time(nullptr);
    auto local = std::asctime(std::localtime(&result));
    std::cout <<local;
    std::cout << "UTC:   " << std::put_time(std::gmtime(&result), "%c %Z") << '\n';
    putenv("TZ=Asia/Singapore");
    local = std::asctime(std::localtime(&result));
    std::cout <<"Asia/Singapore Time "<<local;

}

Output

Thu Sep 14 21:59:37 2017
UTC:   Fri Sep 15 01:59:37 2017 UTC
Asia/Singapore Time Fri Sep 15 09:59:37 2017
Program ended with exit code: 0

Upvotes: 1

Related Questions