how to print future calendar date in C++

Feb 19, 2017 at 2:01am
I've been looking for a way to calculate a future calendar date in C++, but so far no dice.

Basically I want to add 3 days (for standard delivery) OR add one day (for overnight delivery) to the CURRENT time (printed in MM-DD-YYYY format). How do I do this simply in C++?

Output would look like this:

1
2
3
4
5
6
7
8
9
 Would you like overnight delivery [Y/N]? Y
    
    Today's Date: 03-25-2017
    Your Expected Arrival Date: 03-26-2017
    
Would you like overnight delivery [Y/N]? N
    
    Today's Date: 03-25-2017
    Your Expected Arrival Date: 03-28-2017
Last edited on Feb 19, 2017 at 2:03am
Feb 19, 2017 at 2:46am
Using facilities in <ctime> http://en.cppreference.com/w/cpp/header/ctime

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
#include <iostream>
#include <string>
#include <ctime>

// invariant: date is a valid date in MM-DD-YYYY format
// invariant: within the std::time_t epoch (typically dates after 31 dec 1969) 
std::string add_days( std::string date, int ndays )
{
   std::tm tm{} ; // initialise to all zeroes
   tm.tm_mon = std::stoi(date) - 1 ;
   tm.tm_mday = std::stoi( date.substr(3) ) + ndays ;
   tm.tm_year = std::stoi( date.substr(6) ) - 1900 ;

   const auto time_point = std::mktime( std::addressof(tm) ) ;
   tm = *std::localtime( std::addressof(time_point) ) ;

   char buffer[1024] ;
   std::strftime( buffer, sizeof(buffer), "%m-%d-%Y", std::addressof(tm) ) ;
   return buffer ;
}

std::string sub_days( std::string date, int ndays ) { return add_days( date, -ndays ) ; }

int main()
{
    std::string date = "03-29-2017" ;
    for( int delta : { 0, 1, 3, 7, 42, 365+42 } )
    {
        std::cout << date << " + " << delta << " day(s) == " << add_days( date, delta ) << '\n'
                  << date << " - " << delta << " day(s) == " << sub_days( date, delta ) << '\n' ;
    }
}

http://coliru.stacked-crooked.com/a/0664cf719c1ef5a2
http://rextester.com/JOGQ10148
Feb 19, 2017 at 3:30am
Hmm...maybe I'm overreaching, but is there a way to do this such that the computer retrieves and displays the current date for you and the projected date in the same format? Ideally...I would not have to manually input the current date into the machine.
Last edited on Feb 19, 2017 at 3:35am
Feb 19, 2017 at 5:14am
1
2
3
4
5
6
7
8
9
10
11
12
std::string format_date( const std::tm& tm ) // MM-DD-YYYY
{
   char buffer[1024] ;
   std::strftime( buffer, sizeof(buffer), "%m-%d-%Y", std::addressof(tm) ) ;
   return buffer ;
}

std::string today() // current date in MM-DD-YYYY format
{
    std::time_t now = std::time(nullptr) ;
    return format_date( *std::localtime( std::addressof(now) ) ) ;
}

http://coliru.stacked-crooked.com/a/0c360dc4d4fa2eb2
Last edited on Feb 19, 2017 at 5:14am
Topic archived. No new replies allowed.