Convert a string to a date in C++

76,856

Solution 1

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

Solution 2

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.

Solution 3

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).

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

Solution 5

Why not go for a simpler solution using boost

using namespace boost::gregorian;
using namespace boost::posix_time;    
ptime pt = time_from_string("20150917");
Share:
76,856

Related videos on Youtube

Ubervan
Author by

Ubervan

Updated on July 09, 2022

Comments

  • Ubervan
    Ubervan almost 2 years

    I know this may be 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.

  • Everyone
    Everyone over 7 years
    Works well.. With just a little modification this should be the best answer