开发者

Convert a string to a date in C++

I know this may b开发者_如何转开发e simple but being C++ I doubt it will be. How do I convert a string in the form 01/01/2008 to a date so I can manipulate it? I am happy to break the string into the day month year constituents. Also happy if solution is Windows only.


#include <time.h>
char *strptime(const char *buf, const char *format, struct tm *tm);


I figured it out without using strptime.

Break the date down into its components i.e. day, month, year, then:

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 can now be converted to a time_t and be manipulated.


For everybody who is looking for strptime() for Windows, it requires the source of the function itself to work. The latest NetBSD code does not port to Windows easily, unfortunately.

I myself have used the implementation here (strptime.h and strptime.c).

Another helpful piece of code can be found here. This comes originally from Google Codesearch, which does not exist anymore.

Hope this saves a lot of searching, as it took me quite a while to find this (and most often ended up at this question).


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


Why not go for a simpler solution using boost

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


You can utilize the boost library(cross platform)

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

But the format should be as mentioned :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜