【问题标题】:Convert a string to a date in C++在 C++ 中将字符串转换为日期
【发布时间】:2010-09-23 10:19:57
【问题描述】:

我知道这可能很简单,但作为 C++ 我怀疑它会是。如何将 01/01/2008 形式的字符串转换为日期以便我可以操作它?我很高兴将字符串分解为日月年成分。如果解决方案仅适用于 Windows,也很高兴。

【问题讨论】:

    标签: c++ string date


    【解决方案1】:
    #include <time.h>
    char *strptime(const char *buf, const char *format, struct tm *tm);
    

    【讨论】:

      【解决方案2】:

      我没有使用strptime就知道了。

      将日期分解为其组成部分,即日、月、年,然后:

      struct tm  tm;
      time_t rawtime;
      time ( &rawtime );
      tm = *localtime ( &rawtime );
      tm.tm_year = year - 1900;
      tm.tm_mon = month - 1;
      tm.tm_mday = day;
      mktime(&tm);
      

      tm 现在可以转换为time_t 并进行操作。

      【讨论】:

        【解决方案3】:

        对于正在为 Windows 寻找 strptime() 的每个人来说,它需要函数本身的源代码才能工作。不幸的是,最新的 NetBSD 代码无法轻松移植到 Windows。

        我自己使用了实现 here(strptime.h 和 strptime.c)。

        可以找到另一段有用的代码 here。这最初来自 Google Codesearch,现已不存在。

        希望这可以节省大量搜索,因为我花了很长时间才找到这个(而且最常见的是这个问题)。

        【讨论】:

          【解决方案4】:
          #include <time.h>
          #include <iostream>
          #include <sstream>
          #include <algorithm>
          
          using namespace std;
          
          int main ()
          {
            time_t rawtime;
            struct tm * timeinfo;
            int year, month ,day;
            char str[256];
          
            cout << "Inter date: " << endl; 
            cin.getline(str,sizeof(str));
          
            replace( str, str+strlen(str), '/', ' ' );  
            istringstream( str ) >> day >> month >> year;
          
            time ( &rawtime );
            timeinfo = localtime ( &rawtime );
            timeinfo->tm_year = year - 1900;
            timeinfo->tm_mon = month - 1;
            timeinfo->tm_mday = day;
            mktime ( timeinfo );
          
            strftime ( str, sizeof(str), "%A", timeinfo );
            cout << str << endl;
            system("pause");
            return 0;
          }
          

          【讨论】:

          • 效果很好..只需稍作修改,这应该是最好的答案
          【解决方案5】:

          为什么不使用 boost 寻求更简单的解决方案

          using namespace boost::gregorian;
          using namespace boost::posix_time;    
          ptime pt = time_from_string("20150917");
          

          【讨论】:

            【解决方案6】:

            您可以使用 boost 库(跨平台)

            #include <stdio.h>
            #include "boost/date_time/posix_time/posix_time.hpp"
            
            int main()
            {    
            std::string strTime = "2007-04-11 06:18:29.000";
            std::tm tmTime = boost::posix_time::to_tm(boost::posix_time::time_from_string(strTime));
            return 0;
            }
            

            但格式应该如前所述:)

            【讨论】:

              猜你喜欢
              • 2011-04-29
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2015-04-27
              • 2010-12-08
              • 2013-12-22
              相关资源
              最近更新 更多