【问题标题】:C++ - Convert Given UTC Time string to Local time zoneC++ - 将给定的 UTC 时间字符串转换为本地时区
【发布时间】:2017-03-17 10:10:29
【问题描述】:

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

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

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

【问题讨论】:

标签: c++ utc


【解决方案1】:

找到解决方案...

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

【讨论】:

  • strftime(CharLocalTimeofUTCTime, 30, "%Y-%m-%dT%H:%M:%SZ", &amp;tm); 在时间戳末尾加上 Z 表示它是 UTC。但现在是当地时间。
猜你喜欢
  • 2020-09-28
  • 2014-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-31
  • 2010-09-09
  • 2020-11-24
  • 2010-12-18
相关资源
最近更新 更多