C++ - 将给定的 UTC 时间字符串转换为本地时区

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

我们有字符串格式的 UTC 时间,我们需要转换为您当前的时区并采用字符串格式。

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

需要以相同的字符串格式将上述值转换​​为本地时间。 就像在 IST 中一样,它将是 "2017-03-17T15:30:00Z"

找到解决方案...

1) 将String格式的时间转换为time_t

2) 使用"localtime_s" 将utc 转换为本地时间。

3) 使用"strftime" 将本地时间(struct tm 格式)转换为字符串格式。

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);
}