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.
6 Answers
#include <time.h>
char *strptime(const char *buf, const char *format, struct tm *tm);

- 21,522
- 8
- 49
- 87
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).

- 1,057
- 11
- 25
#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;
}

- 31
- 1
-
Works well.. With just a little modification this should be the best answer – Everyone Jan 31 '17 at 08:36
Why not go for a simpler solution using boost
using namespace boost::gregorian;
using namespace boost::posix_time;
ptime pt = time_from_string("20150917");

- 215
- 1
- 12
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 :)

- 6,448
- 2
- 41
- 37