1

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"

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
Dhruvesh Soni
  • 41
  • 1
  • 1
  • 7

1 Answers1

1

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);
}
Dhruvesh Soni
  • 41
  • 1
  • 1
  • 7
  • `strftime(CharLocalTimeofUTCTime, 30, "%Y-%m-%dT%H:%M:%SZ", &tm);` Having the Z at the end of the timestamp communicates it's UTC. But this is local time now. – psyklopz Aug 28 '20 at 19:01