Click here to Skip to main content
15,911,142 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi
I need to do the date comparision in plain C.
one is the char Date_1[8] and other is #defined constant "DATE2"
I want to use most recent date from above 2 dates and store it into a file.

Can anybody help me out.

Thanks in advance. :-O
Posted

If it is allowed
to code the date as "YYYYMMDD",

you could use :) :
#define d2 "19001229"
...
{
...
  char d1[8] = {'2','0','1','0','0','4','0','6'};
  int iResult = memcmp(d1 /*address of date1*/,
                       d2 /*address of date2*/,
                       sizeof(d1) /*=8, length to compare*/);
}
 
Share this answer
 
v2
Thanks for reply.

But my date format is dd/mm/yyyy
How can i compare them?
compare year, month ,date.
I want to use the most recent date. :-O
 
Share this answer
 
Another solution to hold and compare the dates :) :
typedef struct sMydate {
  WORD m_wYear;
  BYTE m_byMonth;
  BYTE m_byDay;
 

  sMydate(WORD wYear, BYTE byMonth, BYTE byDay) {
    m_wYear   = wYear;
    m_byMonth = byMonth;
    m_byDay   = byDay;
  }
 

  int Compare(const sMydate& sAnotherDate) {
    LONG lThisDate = MAKELONG(MAKEWORD(m_byDay, m_byMonth), m_wYear);
    LONG lAnotherDate = MAKELONG(MAKEWORD(sAnotherDate.m_byDay,
                                          sAnotherDate.m_byMonth),
                                 sAnotherDate.m_wYear);
 

    return memcmp(&lThisDate, &lAnotherDate, sizeof(LONG));
  }
} MYDATE, *LPMYDATE;
...
const MYDATE sConstDate(1900, 12, 29);
...
{
...
  MYDATE sLocalDate(2010, 04, 06);
  int iResult = sLocalDate.Compare(sConstDate);
...
}
;
 
Share this answer
 
Poonamol wrote:
But my date format is dd/mm/yyyy
How can i compare them?
compare year, month ,date.
I want to use the most recent date


The following function returns 1 whenever sDate1 is more recent than sDate2.
Please note: error check is left to the reader.


C++
#include <stdlib.h>

int datecmp(char sdate1[], char sdate2[])
{
  unsigned int y[2], m[2], d[2];
  char * pEnd;
  const char * s[2] = {sdate1, sdate2};
  for (int i=0; i<2; i++)
  {
    d[i] = strtoul(s[i], &pEnd, 10);
    m[i] = strtoul(pEnd+1, &pEnd, 10);
    y[i] = strtoul(pEnd+1, NULL, 10);
  }
  if (y[0] < y[1] )
    return -1;
  else if ( y[0] > y[1])
    return 1;
  if (m[0] < m[1] )
    return -1;
  else if ( m[0] > m[1])
    return 1;
  if (d[0] < d[1] )
    return -1;
  else if ( d[0] > d[1])
    return 1;
  return 0;
}


:)
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900