Alex Johnson
Alex Johnson

Reputation: 958

How can I format a date to remove preceding spaces and zeros using put_time()?

My program parses a string representing a date formatted as YYYYMMDD and prints it in the form of dayOfWeek, Month Day, Year. For example, given the string 20131224, the program should print Sunday, December 24, 2013.

The program I have written does just that:

#include <iostream>
#include <sstream>
#include <ctime>
#include <iomanip>

using namespace std;

int main() {
    struct tm tm;
    string s("20131224");
    if (strptime(s.c_str(), "%Y%m%e", &tm)) {
        cout << put_time(&tm, "%A, %B %e, %Y") << endl;
    }
}

My problem is that when given a string with a date with a preceding zero, like 20131204, the output includes an extra space between the month and the day, like so: Sunday, December 4, 2013.

I know that if I use %d instead of %e then that space will be replaced with a zero, but that's not what I want either. I know that removing the space between %B and %e will solve the solution for single digit dates, but it doesn't work for double digit dates (as it will print Sunday, December24, 2013). And I know that I could use some sort of regex search to find and replace that double space, but surely there's a more straightforward solution to this.

How can I remove both the preceding space and zero from a date formatted with put_time()?

Upvotes: 3

Views: 727

Answers (1)

Ralph Tandetzky
Ralph Tandetzky

Reputation: 23620

Try this:

cout << put_time(&tm, tm.tm_mday < 10 ? 
                      "%A, %B%e, %Y" : 
                      "%A, %B %e, %Y" ) << endl;

Upvotes: 2

Related Questions