c++ - Getting offset by 1 day when converting NTP time to date -


i'm trying implement own ntp client.

i can send , recieve ntp messages , need convert "real" time. have created function this, reason fields correct, except day field 1 day behind.

i've done quick calculations pen, paper , calculator , same results there must i'm missing.

here code:

void settime(uint32_t seconds, uint32_t fraction) {     int yearspassed = seconds / (60 * 60 * 24 * 365);      year = 1900 + yearspassed;      int leapyears = yearspassed / 4;      int secondsleft = seconds - yearspassed * 365 * 24 * 60 * 60;      secondsleft -= leapyears * 60 * 60 * 24;      int dayspassed = secondsleft / (60 * 60 * 24);      secondsleft -= dayspassed * 60 * 60 * 24;      int hourspassed = secondsleft / (60*60);      secondsleft -= hourspassed * 60 * 60;      int minutespassed = secondsleft / 60;      secondsleft -= minutespassed * 60;      hour = hourspassed + summertime_offset;     minute = minutespassed;     second = secondsleft;      = (fraction * (pow((float)10,(float)6)) / (pow((float)2,(float)32)));      month = getmonth(dayspassed);     day = getday(month, dayspassed); } 

with code can example time 2015/4/28 14:3:15.351731 date should 29 instead of 28. initial thought calculated wrong leap years , missing 1 day that, appears correct.

edit

code getmonth() , getday(). not implemented yet since wanted write little code possible test works.

int getmonth(int dayspassed) {     if (dayspassed < 32)         return 1;     else if (dayspassed < 60)         return 2;     else if (dayspassed < 91)         return 3;     else if (dayspassed < 121)         return 4;     else if (dayspassed < 152)         return 5;     else          return 6; }  int getday(int month, int dayspassed) {     switch (month)     {     case 1:         return dayspassed;         break;     case 2:         return dayspassed - 31;         break;     case 3:         return dayspassed - 59;         break;     case 4:         return dayspassed - 90;         break;     case 5:         return dayspassed - 120;         break;     default:         return 6;         break;     } } 

you've got fencepost error on dayspast, completed days, , not number of partial days.

consider input of 1 second (heck, better still, make unit test), should resolve 1/1/1900 00:00:01 - give dayspast 0 whilst number of days past, doesn't account current day.

of course, you'll need take account whether current year leap year when calculating day in year; , completeness, , compatibility in year 2100, leap years past algorithm smidge naive.


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -