1 /******************************************************************************** 2 * * 3 * N T P - T i m e * 4 * * 5 ********************************************************************************* 6 * Copyright (C) 2019,2020 by Jeroen van der Zijp. All Rights Reserved. * 7 ********************************************************************************* 8 * This library is free software; you can redistribute it and/or modify * 9 * it under the terms of the GNU Lesser General Public License as published by * 10 * the Free Software Foundation; either version 3 of the License, or * 11 * (at your option) any later version. * 12 * * 13 * This library is distributed in the hope that it will be useful, * 14 * but WITHOUT ANY WARRANTY; without even the implied warranty of * 15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * 16 * GNU Lesser General Public License for more details. * 17 * * 18 * You should have received a copy of the GNU Lesser General Public License * 19 * along with this program. If not, see <http://www.gnu.org/licenses/> * 20 ********************************************************************************/ 21 #include "xincs.h" 22 #include "fxver.h" 23 #include "fxdefs.h" 24 #include "fxmath.h" 25 #include "fxascii.h" 26 #include "FXString.h" 27 #include "FXSystem.h" 28 29 30 /* 31 Notes: 32 33 - Conversions between Network Time Protocol (NTP) time and Unix Epoch Time. 34 */ 35 36 37 using namespace FX; 38 39 /*******************************************************************************/ 40 41 namespace FX { 42 43 // Offset from Epoch to 1-Jan-1900 @ 00:00:00 UTC 44 const FXTime JANUARY1900=-FXLONG(2208988800000000000); 45 46 // Offset from Epoch to 7-Feb-2036 @ 06:28:16 UTC 47 const FXTime FEBRUARY2036=+FXLONG(2085978496000000000); 48 49 50 // Convert NTP format (ssss:ffff) to nanoseconds since Unix Epoch timeFromNTPTime(FXulong ntptime)51FXTime FXSystem::timeFromNTPTime(FXulong ntptime){ 52 FXTime secs=(ntptime>>32)&0xFFFFFFFF; 53 FXTime frac=ntptime-(secs<<32); 54 FXTime nano=(frac*1000000000+2147483647)>>32; 55 return (secs&0x80000000) ? (secs*1000000000+nano+JANUARY1900) : (secs*1000000000+nano+FEBRUARY2036); 56 } 57 58 59 // Convert utc in nanoseconds since Unix Epoch to NTP (ssss:ffff) ntpTimeFromTime(FXTime utc)60FXulong FXSystem::ntpTimeFromTime(FXTime utc){ 61 FXlong base=utc-FEBRUARY2036; 62 FXlong secs=(0<=base ? base : base-999999999)/1000000000; 63 FXlong nano=base-secs*1000000000; 64 FXlong frac=((nano<<32)+500000000)/1000000000; 65 return (secs<<32)+frac; 66 } 67 68 } 69 70