home *** CD-ROM | disk | FTP | other *** search
/ Mastering MFC Development / MMD.ISO / labs / c13 / lab01 / ex01 / mdy.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  1997-02-20  |  2.0 KB  |  74 lines

  1. // mdy.cpp : Implementation of Cmdy
  2. #include "stdafx.h"
  3. #include "MoDaYrX.h"
  4. #include "mdy.h"
  5.  
  6. #include <stdio.h>    // for sscanf
  7.  
  8. /////////////////////////////////////////////////////////////////////////////
  9. // Cmdy
  10.  
  11. STDMETHODIMP Cmdy::MDYfromBSTR(BSTR bstrDate, short * pnM, short * pnD, short * pnY)
  12. {
  13.     short nMonth, nDay, nYear, nFields;
  14.     
  15.     nMonth = nDay = nYear = 0;
  16.     _bstr_t bstr(bstrDate);
  17.     nFields = sscanf( ( char * ) bstr, "%hd/%hd/%hd",
  18.                     & nMonth, & nDay, & nYear );
  19.     if ( 3 == nFields )    //Did we get three values?
  20.     {
  21.         if ( nYear < 100 )
  22.             nYear += 1900;
  23.         * pnY = nYear;
  24.         * pnM = nMonth;
  25.         * pnD = nDay;
  26.         return S_OK;    
  27.     }
  28.     return S_FALSE;
  29. }
  30.  
  31. STDMETHODIMP Cmdy::ValidateMDY(BSTR * pbstrMessage, short nM, short nD, short nY)
  32. {
  33.     char caBuff[80];
  34.     _bstr_t bstrMsg1, bstrMsg2;
  35.     short nMaxDays = 30;    //Usually they all have 30 days except Feb
  36.     short nMonth = nM;
  37.     
  38.     nMaxDays += nMonth < 8 ? //Odd months are longer until July
  39.         nMonth & 1 : ! ( nMonth & 1 );
  40.     if ( 2 == nMonth )    //February
  41.     {
  42.         short nLeapYear =
  43.             0 == nY % 4;            //Leap years always evenly divisible by 4
  44.         if ( nLeapYear )
  45.             nLeapYear =
  46.                 0 == nY % 100    //If the year is even div by 100
  47.                 ?
  48.                 0 == nY % 400    //Then it must also be even div by 400
  49.                 :
  50.                 1;
  51.  
  52.         nMaxDays = 28 + nLeapYear;    //Add a day for leap years
  53.     }
  54.     if ( nMonth < 1 || nMonth > 12 )
  55.     {
  56.         bstrMsg1 = "Month must be between 1 and 12\n";
  57.         nMaxDays = 31;    //Not more than 31 days in an invalid month
  58.     }
  59.     if ( nD < 1 || nD > nMaxDays )
  60.     {
  61.         wsprintf( caBuff, "\nDay must be between 1 and %hd", nMaxDays );
  62.         bstrMsg2 = caBuff;
  63.     }
  64.     
  65.     if ( ! bstrMsg1 && ! bstrMsg2 )    //If neither contains a message
  66.         return S_OK;                //No problems noted
  67.     
  68.     _bstr_t msg( bstrMsg1 );        //String with the first message (or NULL)
  69.     msg += bstrMsg2;                //Concatenate second message (or NULL)
  70.     * pbstrMessage = msg;            //Modify parameter to contain message
  71.  
  72.     return S_FALSE;                    //Something was wrong
  73. }
  74.