How to convert Date to Unix format ?

What is Unix Date ?

Present date is stored in 16-bit modbus register as follows:

Bits 0 - 4       Day of Month
Bits 5 - 8       Month of Year
Bits 9 - 15     (Year  -  2000)  (0 to 128  ==  2000 to 2128 )


How to conver this date to unix format ?

Thank you!
LVL 1
naseeamAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

jkrCommented:
You could use 'mktime()' (http://www.cplusplus.com/reference/ctime/mktime/) for that, e.g.

#include <time.h>

uint16_t regtime; // from modbus

struct tm t;

t.tm_mday = regtime & 0x1f;
t.tm_mon = (regtime >> 5) & 0x07 -1;
t.tm_year = (regtime >> 9) & 0x3f + 100; // UNIX date is from 1900

time_t ut = mktime(&t);

Open in new window

0
naseeamAuthor Commented:
Thanks for great and concise response.

For tm_mon, I believe bitwise and with 0x0f instead of 0x07.
For tm_year, I believe bitwise and with 0x7f instead of 0x3f.

In our system, time_t is declared as follows:
typedef    unsigned int    time_t;

time_t is only two bytes.  Is that sufficent to store unix time ?
0
jkrCommented:
>>For tm_mon, I believe bitwise and with 0x0f instead of 0x07.
>>For tm_year, I believe bitwise and with 0x7f instead of 0x3f.

Yes, you are right, since these are 4 bits and 6 bits respectively, didn't count right :-/

>>time_t is only two bytes.  Is that sufficent to store unix time ?

As an 'unsigned int', it's 4 bytes, and that should be enough. Only two bytes would indeed mean trouble.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C++

From novice to tech pro — start learning today.