现在的位置: 首页 > 综合 > 正文

时间获取,以及时间格式字符串转化

2013年05月24日 ⁄ 综合 ⁄ 共 1751字 ⁄ 字号 评论关闭

std::string IntToString(int i)
  {
   char tmpBuf[20];
   itoa(i, tmpBuf, 10);
   return std::string(tmpBuf);
  }

 

int StringToInt(std::string str)
  {
   return atoi(str.c_str());
  }

 

 

//将时间转换为"年-月-日 时:分:秒"字符串格式
  std::string TimeToString(tm* time, std::string DaySplite = "-", std::string DayTimeSplite = " ", std::string TimeSplite = ":");

  std::string TimeToString(tm* time, std::string DaySplite, std::string DayTimeSplite, std::string TimeSplite)
  {
   string tStr = IntToString(time->tm_year + 1900);
   tStr += DaySplite;
   if(IntToString(time->tm_mon + 1).length() == 1)
    tStr += "0";
   tStr += IntToString(time->tm_mon + 1);
   tStr += DaySplite;
   if(IntToString(time->tm_mday).length() == 1)
    tStr += "0";
   tStr += IntToString(time->tm_mday);
   tStr += DayTimeSplite;
   if(IntToString(time->tm_hour).length() == 1)
    tStr += "0";
   tStr += IntToString(time->tm_hour);
   tStr += TimeSplite;
   if(IntToString(time->tm_min).length() == 1)
    tStr += "0";
   tStr += IntToString(time->tm_min);
   tStr += TimeSplite;
   if(IntToString(time->tm_sec).length() == 1)
    tStr += "0";
   tStr += IntToString(time->tm_sec);
   return tStr;
  }

 

//将格林威治时间(1900.1.1起到现在秒数)转化为"年-月-日 时:分:秒"的格式
  string _API TimeToString(time_t max);

 

string TimeToString(time_t max)
  {
   time_t value = max;
   tm* time = localtime(&value);
   string tStr = TimeToString(time,"-"," ",":");
   return tStr;
  }
  //将"年-月-日 时:分:秒"格式的时间转化为格林威治时间(1900.1.1起到现在秒数)
  time_t ConvertMyTimeToTimet(string strTime);

 

time_t ConvertMyTimeToTimet(string strTime)
  {
   tm t;
   memset(&t, 0, sizeof(t));
   t.tm_year = StringToInt(strTime.substr(0,4)) - 1900;
   t.tm_mon =  StringToInt(strTime.substr(5,2)) - 1;
   t.tm_mday = StringToInt(strTime.substr(8,2));
   t.tm_hour = StringToInt(strTime.substr(11,2));
   t.tm_min = StringToInt(strTime.substr(14,2));
   t.tm_sec = StringToInt(strTime.substr(17,2));
   return _mktime64(&t);
  }

【上篇】
【下篇】

抱歉!评论已关闭.