Solved

# How to convert Date to Unix format ?

Posted on 2013-09-23
Medium Priority
431 Views
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!
0
Question by:naseeam
• 2

LVL 86

Expert Comment

ID: 39515952
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);
``````
0

LVL 1

Author Comment

ID: 39516431
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

LVL 86

Accepted Solution

jkr earned 2000 total points
ID: 39516450
>>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

## Featured Post

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.