[Last Call] Learn about multicloud storage options and how to improve your company's cloud strategy. Register Now

x
?
Solved

looking for end of month function

Posted on 2004-10-28
11
Medium Priority
?
223 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
Comment
Question by:justinY
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
11 Comments
 
LVL 12

Expert Comment

by:OnegaZhang
ID: 12440229
#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
ID: 12447285
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
ID: 12449664
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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:justinY
ID: 12453773
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
ID: 12454330
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
ID: 12454364
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
ID: 12454607
Georg,

I have compiling errors for your code.
0
 

Author Comment

by:justinY
ID: 12455690
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
ID: 12456128
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:
Sys_Prog earned 1000 total points
ID: 12458611
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
ID: 12459127
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

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
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.
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.

650 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