Link to home
Start Free TrialLog in
Avatar of naseeam
naseeamFlag for United States of America

asked on

How to convert date to ISO 1806 format ?

/* A 16-bit date is read over modbus.  Date fields are as follows:
Bits 0 - 4      Day of Month
Bits 5 - 8      Month of Year
Bits 9 - 15    Year   ( 0 to 128 == 2000 to 2128 )  */
unsigned short responseBuffer[128];

/* responseBuffer[0] contains the 16-bit date read over modbus */
dateFunc ( (char *) &responseBuffer[0], 2 );

Result  dateFunc (const char * val, unsigned short size)
{
    /* convert date read over modbus to ISO 8601 format */
   /* enter code here */


} 

Open in new window

Avatar of naseeam
naseeam
Flag of United States of America image

ASKER

ISO 8601 date format is:   "2014-02-05"  or more generically "YYYY-MM-DD"
Avatar of jkr
You could do that using bitwise operators, e.g.

bool dateFunc (const char val, char* iso8601_buf, unsigned short size) // pass 'val' as a single byte
{
    /* convert date read over modbus to ISO 8601 format */
/* A 16-bit date is read over modbus.  Date fields are as follows:
Bits 0 - 4      Day of Month
Bits 5 - 8      Month of Year
Bits 9 - 15    Year   ( 0 to 128 == 2000 to 2128 )  */

  unsigned short usDay =   val & 0x0F; // isolate bits 0-4
  unsigned short usMon = (val >> 4) & 0x07; // isolate bits 5-8
  unsigned short usYear = (val >> 9) & 0x3F; // isolate bits 9-15 (bitwise AND is not strictly necessary

  usYear += 2000; // add offset

  if ( size < 11) return false; // buffer not large enough;

  sprintf(iso8601_buf,"%4.4d-%2.2d-%2.2d",usYear,usMon,usDay);

  return true;
} 

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial