Solved

looking for end of month function

Posted on 2004-10-28
210 Views
Last Modified: 2012-06-27
Hi experts,

I am looking for a function.
If  end of month, then print next date. it should be the first day of next month.

Thanks
0
Question by:justinY
    11 Comments
     
    LVL 12

    Expert Comment

    by:OnegaZhang
    #include "boost/date_time/gregorian/gregorian.hpp"
    #include "boost/date_time/date_parsing.hpp"
    #include <iostream>
    int main()
    {

         using namespace boost::gregorian;
         std::string s;
         std::cout << "Enter the day YYYY-MM-DD (eg: 2002-02-01): ";
         std::cin >> s;
         try {
              date_duration oneday(1);
              date birthday(boost::date_time::parse_date<date>(s));
              date newdate = birthday+oneday;
              if(1==newdate.day())
              {
                   std::cout<<birthday<<" is end of month, the day after it is "<<newdate<<std::endl;
              }
              else
              {
                   std::cout<<birthday<<" is not end of month"<<std::endl;
              }
         }
         catch(...) {
              std::cout << "Bad date entered: " << s << std::endl;
         }
         system("PAUSE");
         return 0;
    };
    0
     

    Author Comment

    by:justinY
    Hi,
    Do you have any other ways to do the end of month ?
    Sorry, for now I am really not comfortable with boost library.
    0
     
    LVL 3

    Expert Comment

    by:georg74
    boost is really good, using it every day,
    you just have to find a version that is compilable with you r compiler :-)

    what date representation do you use now?

    if you use day count (from some datum, for example 1 = 1970-01-01),
    then next day is simply +1

    if you want the formula for
        bool is_end_of_month(unsigned short y, unsigned short m, unsigned short d)
    then you first have to define "end of month".

    if it is "the last day of the month", then it is simple. :-)
    all months have fixed number of days except february
    february has 28 days except in a leap year, when it has 29 days.

    first day in the next month is the 1st of ((month) % 12 + 1)

    cheers,
    georg
    0
     

    Author Comment

    by:justinY
    Thanks
    I found part of LastDay function, it is not complete.
    How can I solve my problem with this function ?


    int Date::LastDay () const {
                                static int eom[12] = { 31,28,31,30,31,30,31,31,30,31,30,31};
                                if (IsLeapYear() ==true)  eom[1] = 29;
                                return eom[ _Month - 1 ];
    }
    0
     
    LVL 3

    Expert Comment

    by:georg74
    the code you posted returns the number of days for the current month.
    it assumes that
    - there is a function IsLeapYear() which returns true if the (current) year is a leap year.
    - there is a global variable _Month holding the (current) month.

    anyway, i have to say, that's bad programming style.

    please tell me what date(s) do you want to check.
    just the current date?
    arbitrary date?
    do I understand correctly that you want to check for a date if it is the last day in month?

    IIUC, you need functions
        bool IsLeapYear(int year);
        int days_in_month(int year, int month);

    bool is_last_day_in_month(int year, int month, int day)
    {
        return day == days_in_month(year, month);
    }

    void next_day(int & year, int & month, int & day)
    {
        if (is_last_day_in_month(int year, int month, int day)) {
            day = 1;
            if (month == 12) {
                month = 1;
                ++ year;
            }
            else
                ++month;
        }
        else
            ++day;
    }

    hth,
    georg
    0
     

    Author Comment

    by:justinY
    Thanks, georg,

    I want to check a date, if its end of month, then print the 1st day of next month. if its not end of month, then just print it.

     
    0
     

    Author Comment

    by:justinY
    Georg,

    I have compiling errors for your code.
    0
     

    Author Comment

    by:justinY
    Hi guys,
    this is my code of tesing last day of month. no compiling errors, but not the result i am expecting. whats wrong ? thanks

    bool LeapYear ( int Year )
    {
      bool LeapYear= false;
              if ((Year%4==0 ) && ( Year %100 != 0) || ( Year %400 ==0 ))
              LeapYear = true;

              return LeapYear;

    }

    int DaysPerMonth(int m, int Year)
    {
       int dpm=(1<<(1<<(1<<1))+1)-1;
       if ((m%(1<<1)==0)&&(m<(1<<(1<<1)+1)-1) ||
           (m%(1<<1)==1)&&(m>(1<<(1<<1)+1))) dpm--;
       if (m==(1<<1)) {
          dpm--;
          if (!LeapYear(Year))
             dpm--;
       }
       return dpm;
    }


    /*
    int DaysPerMonth(int m, int Year)
    {
      if (m == 2)
      {
        if (LeapYear(Year)) return 29;
        return 28;
      }
      if (m >= 8) m--;
      return ((m & 1)?31:30);
    }
    */
    bool is_last_day_in_month(int year, int month, int day)
    {
        return day == DaysPerMonth(year, month);
    }


    int main()
    {
      string sdate = "10282004";

    int m = atoi(sdate.substr(0, 2).c_str());
    int d = atoi(sdate.substr(2, 2).c_str());
    int Y = atoi(sdate.substr(4, 4).c_str());
    struct tm date = { 0 };
    date.tm_mday = d;
    date.tm_mon = m - 1;
    date.tm_year = Y - 1900;
    time_t tt = mktime(&date);
    struct tm* pDate = localtime(&tt);
    int wday = pDate->tm_wday; // 1 = monday, 2 = tuesday, ...
    date.tm_mday++; // works with 02292004 and 12312003 as well
    time_t ntt = mktime(&date);
    struct tm* pNextDate = localtime(&ntt);

    char szDate[10];
    stringstream oss1;


      if ( (is_last_day_in_month(Y, m, d)) == true )

          strftime(szDate,10,"%m%d%Y",pNextDate);
          oss1 << szDate;

           cout << oss1.str().c_str() << endl;
            
      return 0;
    }
    0
     
    LVL 3

    Expert Comment

    by:georg74
    hi justinY,

    > I have compiling errors for your code.

    sorry, that was a syntax error, see correction below.

    > int DaysPerMonth(int m, int Year)
    > {
    >    int dpm=(1<<(1<<(1<<1))+1)-1;
    >    if ((m%(1<<1)==0)&&(m<(1<<(1<<1)+1)-1) ||
    >        (m%(1<<1)==1)&&(m>(1<<(1<<1)+1))) dpm--;
    >    if (m==(1<<1)) {
    >       dpm--;
    >       if (!LeapYear(Year))
    >          dpm--;
    >    }
    >    return dpm;
    > }

    omg, where did you get that?!? :-))
    is someone making fun of you, giving you code that is intentionally made unreadable?

    I'll just translate it into readable code (original lines commented):

    int DaysPerMonth(int m, int Year)
    {
       // int dpm=(1<<(1<<(1<<1))+1)-1;
       int dpm = 31;

       // if ((m%(1<<1)==0)&&(m<(1<<(1<<1)+1)-1) ||
       //  (m%(1<<1)==1)&&(m>(1<<(1<<1)+1))) dpm--;
       if (m % 2 == 0 && m < 7 || m % 2 == 1 && m > 8)
          dpm--;

       if (m == 2) {    // if (m==(1<<1)) {
          dpm--;
          if (! LeapYear(Year))
             dpm--;
       }
       return dpm;
    }

    the function you commented out is o.k. as well.


    let's write your LeapYear function in a better style:

    bool LeapYear ( int Year )
    {
       return Year % 4 == 0 && Year % 100 != 0 || Year % 400 == 0;
    }


    let me correct my next_day() function (error was in the if line):

    void next_day(int & year, int & month, int & day)
    {
        if (is_last_day_in_month(year, month, day)) {
            day = 1;
            if (month == 12) {
                month = 1;
                ++ year;
            }
            else
                ++month;
        }
        else
            ++day;
    }

    at last, you need following in the main function:

    ...
    if (is_last_day_in_month(Y, m, d)) {
       next_day(Y, m, d);
    }
    cout << "result: " << m << "/" << d << "/" << Y << endl;

    adjust the formatting if needed.
    You don't need mktime, localtime nor strftime...

    gl,
    georg
    0
     
    LVL 10

    Accepted Solution

    by:
    There were a couple of errors in your code which I fixed

    1.

    bool is_last_day_in_month(int year, int month, int day)
    {
        return day == DaysPerMonth( month, year);
    }

    should be

    bool is_last_day_in_month(int year, int month, int day)
    {
        return day == DaysPerMonth( year, month);
    }
    since DaysPerMonth() expects year first and then month



    2.

    I embedded a couple of statements in braces, these statements are the ones for printing the next months date, so should be in if condition

    if ( (is_last_day_in_month(Y, m, d)) == true )
    strftime(szDate,10,"%m%d%Y",pNextDate);
         oss1 << szDate;

          cout << oss1.str().c_str() << endl;


    should be


        if ( (is_last_day_in_month(Y, m, d)) == true ) {
            strftime(szDate,10,"%m%d%Y",pNextDate);
            oss1 << szDate;
            cout << oss1.str().c_str() << endl;
        }  


    HTH

    Amit
    0
     
    LVL 3

    Expert Comment

    by:georg74
    just one more hint - for statement
    if (<boolean expression>) ...
    you don't need to compare the expression with true.

    don't:         if (is_last_day_of_month(...) == true) { ...

    just do        if (is_last_day_of_month(...)) { ...

    georg
    0

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

     Java Android Coding Bundle

    Whether you're an Apple user or Android addict, learning to code for the Android platform is an extremely valuable, in-demand skill. It all starts with Java, the language behind the apps and games that make Android the top platform it is today.

    Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
    Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
    The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
    The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.

    913 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    12 Experts available now in Live!

    Get 1:1 Help Now