convert string to Year and Month

Hello everyone

Could anyone please help me convert and string into Year and Month (not day)? The code I use for converting a string into a proper year-month-day is as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
bool get_time(const std::string& s, time_t& time)
{	
	tm date;
    	date.tm_isdst = 0;
    	std::istringstream iss(s);
    	std::string line;
    	char c;
	
    	// Read date as a whole string up to '-' (yyyymmdd)
    	if(!(std::getline(iss, line, ' ') >> c))
    	{
		return false;
	}
	
    	if(line.size() != 10)
    	{
		return false; // illegal data, should be 8 characters
	}

    	// pick out pieces of date
    	if(!(std::istringstream(line.substr(0, 4)) >> date.tm_year))
    	{
		return false;
	}
	
    	if(!(std::istringstream(line.substr(5, 2)) >> date.tm_mon)) 
    	{
		return false;
	}
	
    	if(!(std::istringstream(line.substr(8, 2)) >> date.tm_mday)) 
    	{
		return false;
	}
	
    	// read time
    	if(!(iss >> date.tm_hour >> c))
    	{
		return false;
	}
	
    	if(!(iss >> date.tm_min >> c)) 
    	{
		return false;
	}
	
    	if(!(iss >> date.tm_sec >> c)) 
    	{
		return false;
	}
	
    	// adjust to struct tm spec bounds
    	date.tm_mon -= 1; // needs to be 0-11 (not 1-12)
    	date.tm_year -= 1900;
    	time = mktime(&date);
	
    	return true;
}


How do I use it for converting a string like 1209 which means year 2012 and month september. I want to find which one is the smallest/near time e-g 1103 (year-2011 and month-March) is nearer than 1209 (year-2012 and month-September) and I want the method below to return the near time.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
bool time_diff(const std::string& a, const std::string& z, time_t& diff)    // calculates time difference
{    	
    	time_t atime;
    	time_t ztime;
	
    	if(get_time(a, atime) && get_time(z, ztime))
    	{
       		if(atime < ztime)
		{
			return true;
		}
	}
    	
    	return false;   	
}

Last edited on
Topic archived. No new replies allowed.