Dhruvesh Soni
Dhruvesh Soni

Reputation: 41

C++ - Convert Given UTC Time string to Local time zone

We have string format UTC Time and we need to convert to Your Current time zone and in string format.

string strUTCTime = "2017-03-17T10:00:00Z";

Need to Convert above value to Local time in same string format. Like in IST it would be "2017-03-17T15:30:00Z"

Upvotes: 1

Views: 16609

Answers (1)

Dhruvesh Soni
Dhruvesh Soni

Reputation: 41

Got Solution...

1) Convert String formatted time to time_t

2) use "localtime_s" to Convert utc to local time.

3) use "strftime" to convert local time (struct tm format) to string format.

int main()
{
   std::string strUTCTime = "2017-03-17T13:20:00Z";
   std::wstring wstrUTCTime = std::wstring(strUTCTime.begin(),strUTCTime.end());
   time_t utctime = getEpochTime(wstrUTCTime.c_str());
   struct tm tm;
   /*Convert UTC TIME To Local TIme*/
   localtime_s(&tm, &utctime);
   char CharLocalTimeofUTCTime[30];
   strftime(CharLocalTimeofUTCTime, 30, "%Y-%m-%dT%H:%M:%SZ", &tm);
   string strLocalTimeofUTCTime(CharLocalTimeofUTCTime);
   std::cout << "\n\nLocal To UTC Time Conversion:::" << strLocalTimeofUTCTime;
}

std::time_t getEpochTime(const std::wstring& dateTime) 
{

     /* Standard UTC Format*/
     static const std::wstring dateTimeFormat{ L"%Y-%m-%dT%H:%M:%SZ" };

     std::wistringstream ss{ dateTime };
     std::tm dt;
     ss >> std::get_time(&dt, dateTimeFormat.c_str());

     /* Convert the tm structure to time_t value and return Epoch. */
     return _mkgmtime(&dt);
}

Upvotes: 1

Related Questions