DateTime with ODBC

Here is my solution for a (little) problem using ODBC and date & time (for VC++ 4.0 & 5.0).

If using ODBC & date/time fields in a typical CRecordView, ClassWizard automatically
binds a CTime object to the specific recordset. This object has few limits, but the
most important is: there is no way to attach an Edit control in a CRecordView to that field.

With this code, it is possible to bind a date/time field to an Edit control using all
MFC utilities, just like string parsing, data validation, data automatic set/get and so on.

To implement this function you have to do following steps:

1. Add date.h & date.cpp to your project

2. #include “date.h” in your CMyRecordView.cpp

3. Modify CMyRecordView::DoDataExchange( CDataExchange* pDX) as following


void CMyRecordView::DoDataExchange(CDataExchange* pDX)
{
CRecordView::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CEsamiObiettiviView)
DDX_FieldText(pDX, IDC_EDT_NOTE, m_pSet->m_Note, m_pSet);
DDV_MaxChars(pDX, m_pSet->m_Note, 256);


//}}AFX_DATA_MAP
DDX_FieldDate( pDX, IDC_EDT_DATE, m_pSet->m_Date, m_pSet );
}

4. Modify CMyRecordSet as follows:

CTime m_Date becomes TIMESTAMP_STRUCT m_Date

5. Find CMyOwnApp::InitInstance() and add setlocale( LC_ALL, “.OCP” )
This function helps you to use the ControlPanel setup for date & time
representations (don’t forget to #include “locale.h”).

6. That’s all!

Reading the date.cpp it is possible to find three important functions:


DDX_FieldDate(…)
GetDate(…)
SetDate(…)

This is an easy way to create your own bind method with a particular control
& table fields: DDX_FieldsXYZ executes the controls; GetXYZ retrieves data
from your control (don’t forget to create a validation routine) and SetXYZ
displays data in the format you prefer.

Following source contains two functions DDX_FieldDate for date only, and
DDX_FieldDateTime for date and time too.

I test it only on Access DB via ODBC, could someone tests this code with
SQLServer or other DBServer (via ODBC too)?

Download source – 3 KB

Date Last Updated: April 3, 1999

More by Author

Must Read