1 // sg_time.cxx -- data structures and routines for managing time related stuff.
3 // Written by Curtis Olson, started August 1997.
5 // Copyright (C) 1997 Curtis L. Olson - http://www.flightgear.org/~curt
7 // This library is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU Library General Public
9 // License as published by the Free Software Foundation; either
10 // version 2 of the License, or (at your option) any later version.
12 // This library is distributed in the hope that it will be useful,
13 // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // Library General Public License for more details.
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
25 # include <simgear_config.h>
28 #include <simgear/compiler.h>
30 #include <errno.h> // for errno
39 #ifdef HAVE_SYS_TIME_H
40 # include <sys/time.h> // for get/setitimer, gettimeofday, struct timeval
42 #ifdef HAVE_SYS_TIMEB_H
43 # include <sys/timeb.h> // for ftime() and struct timeb
46 # include <unistd.h> // for gettimeofday()
49 #include <math.h> // for NAN
51 #include <simgear/constants.h>
52 #include <simgear/debug/logstream.hxx>
53 #include <simgear/misc/sg_path.hxx>
55 #include "sg_time.hxx"
57 #include "lowleveltime.h"
59 #define DEGHR(x) ((x)/15.)
60 #define RADHR(x) DEGHR(x*SGD_RADIANS_TO_DEGREES)
64 static const double MJD0 = 2415020.0;
65 static const double J2000 = 2451545.0 - MJD0;
66 static const double SIDRATE = 0.9972695677;
68 // tzContainer stores all the current Timezone control points/
69 std::auto_ptr<SGTimeZoneContainer> static_tzContainer;
71 void SGTime::init( const SGGeod& location, const SGPath& root, time_t init_time )
78 cur_time = time(NULL);
81 SG_LOG( SG_EVENT, SG_DEBUG,
82 "Current greenwich mean time = " << asctime(gmtime(&cur_time)));
83 SG_LOG( SG_EVENT, SG_DEBUG,
84 "Current local time = " << asctime(localtime(&cur_time)));
86 if ( !root.isNull()) {
87 if (!static_tzContainer.get()) {
89 zone.append( "zone.tab" );
90 SG_LOG( SG_EVENT, SG_INFO, "Reading timezone info from: "
92 static_tzContainer.reset(new SGTimeZoneContainer( zone.c_str() ));
95 SGTimeZone* nearestTz = static_tzContainer->getNearest(location);
98 name.append( nearestTz->getDescription() );
99 zonename = name.str();
100 SG_LOG( SG_EVENT, SG_DEBUG, "Using zonename = " << zonename );
106 SGTime::SGTime( const SGGeod& location, const SGPath& root,
109 init(location, root, init_time);
112 SGTime::SGTime( const SGPath& root ) {
113 init( SGGeod(), root, 0 );
118 init( SGGeod(), SGPath(), 0 );
127 // given Julian Date and Longitude (decimal degrees West) compute
128 // Local Sidereal Time, in decimal hours.
130 // Provided courtesy of ecdowney@noao.edu (Elwood Downey)
131 static double sidereal_precise( double mjd, double lng )
133 /* printf ("Current Lst on JD %13.5f at %8.4f degrees West: ",
136 // convert to required internal units
137 lng *= SGD_DEGREES_TO_RADIANS;
139 // compute LST and print
140 double gst = sgTimeCalcGST( mjd );
141 double lst = gst - RADHR( lng );
142 lst -= 24.0 * floor( lst / 24.0 );
143 // printf ("%7.4f\n", lstTmp);
149 // return a courser but cheaper estimate of sidereal time
150 static double sidereal_course( time_t cur_time, const struct tm *gmt, double lng )
152 time_t start_gmt, now;
153 double diff, part, days, hours, lstTmp;
156 start_gmt = sgTimeGetGMT(gmt->tm_year, 2, 21, 12, 0, 0);
158 diff = (now - start_gmt) / (3600.0 * 24.0);
160 part = fmod(diff, 1.0);
162 hours = gmt->tm_hour + gmt->tm_min/60.0 + gmt->tm_sec/3600.0;
164 lstTmp = (days - lng)/15.0 + hours - 12;
166 while ( lstTmp < 0.0 ) {
173 /** Deprecated method. To be removed after the next release... */
174 void SGTime::update( double lon_rad, double lat_rad, time_t ct, long int warp )
176 const SGGeod& location = SGGeod::fromRad(lon_rad, lat_rad);
177 update(location, ct, warp);
180 // Update the time related variables
181 void SGTime::update( const SGGeod& location, time_t ct, long int warp )
183 double gst_precise, gst_course;
189 // get current Unix calendar time (in seconds)
190 // warp += warp_delta;
192 cur_time = ct + warp;
194 cur_time = time(NULL) + warp;
197 // get GMT break down for current time
199 memcpy( gmt, gmtime(&cur_time), sizeof(tm) );
200 // calculate modified Julian date starting with current
201 mjd = sgTimeCurrentMJD( ct, warp );
203 // add in partial day
204 mjd += (gmt->tm_hour / 24.0) + (gmt->tm_min / (24.0 * 60.0)) +
205 (gmt->tm_sec / (24.0 * 60.0 * 60.0));
207 // convert "back" to Julian date + partial day (as a fraction of one)
210 // printf(" Current Longitude = %.3f\n", FG_Longitude * SGD_RADIANS_TO_DEGREES);
212 // Calculate local side real time
213 if ( gst_diff < -100.0 ) {
214 // first time through do the expensive calculation & cheap
215 // calculation to get the difference.
216 SG_LOG( SG_EVENT, SG_DEBUG, " First time, doing precise gst" );
217 gst_precise = gst = sidereal_precise( mjd, 0.00 );
218 gst_course = sidereal_course( cur_time, gmt, 0.00 );
220 gst_diff = gst_precise - gst_course;
222 lst = sidereal_course( cur_time, gmt,
223 -location.getLongitudeDeg() ) + gst_diff;
225 // course + difference should drift off very slowly
226 gst = sidereal_course( cur_time, gmt, 0.00 ) + gst_diff;
227 lst = sidereal_course( cur_time, gmt,
228 -location.getLongitudeDeg() ) + gst_diff;
233 // Given lon/lat, update timezone information and local_offset
234 void SGTime::updateLocal( const SGGeod& aLocation, const string& root ) {
235 SGGeod location(aLocation);
236 if (!aLocation.isValid()) {
241 time_t aircraftLocalTime;
242 SGTimeZone* nearestTz = static_tzContainer->getNearest(location);
244 zone.append ( nearestTz->getDescription() );
245 zonename = zone.str();
247 //Avoid troubles when zone.tab hasn't got the right line endings
248 if (zonename[zonename.size()-1] == '\r')
250 zonename[zonename.size()-1]=0;
251 zone.set( zonename );
254 currGMT = sgTimeGetGMT( gmtime(&cur_time) );
255 aircraftLocalTime = sgTimeGetGMT( (fgLocaltime(&cur_time, zone.c_str())) );
256 local_offset = aircraftLocalTime - currGMT;
257 // cout << "Using " << local_offset << " as local time offset Timezone is "
258 // << zonename << endl;
262 // given a date in months, mn, days, dy, years, yr, return the
263 // modified Julian date (number of days elapsed since 1900 jan 0.5),
264 // mjd. Adapted from Xephem.
265 double sgTimeCalcMJD(int mn, double dy, int yr) {
268 // internal book keeping data
269 static double last_mjd, last_dy;
270 static int last_mn, last_yr;
275 if (mn == last_mn && yr == last_yr && dy == last_dy) {
280 y = (yr < 0) ? yr + 1 : yr;
286 if (yr < 1582 || (yr == 1582 && (mn < 10 || (mn == 10 && dy < 15)))) {
295 c = (long)((365.25*y) - 0.75) - 694025L;
297 c = (long)(365.25*y) - 694025L;
300 d = (int)(30.6001*(m+1));
302 mjd = b + c + d + dy - 0.5;
313 // return the current modified Julian date (number of days elapsed
314 // since 1900 jan 0.5), mjd.
315 double sgTimeCurrentMJD( time_t ct, long int warp ) {
317 struct tm m_gmt; // copy of system gmtime(&time_t) structure
318 struct tm *gmt = &m_gmt;
320 // get current Unix calendar time (in seconds)
321 // warp += warp_delta;
324 cur_time = ct + warp;
326 cur_time = time(NULL) + warp;
329 // get GMT break down for current time
330 memcpy( gmt, gmtime(&cur_time), sizeof(tm) );
332 // calculate modified Julian date
333 // t->mjd = cal_mjd ((int)(t->gmt->tm_mon+1), (double)t->gmt->tm_mday,
334 // (int)(t->gmt->tm_year + 1900));
335 double mjd = sgTimeCalcMJD( (int)(gmt->tm_mon+1), (double)gmt->tm_mday,
336 (int)(gmt->tm_year + 1900) );
342 // given an mjd, calculate greenwich mean sidereal time, gst
343 double sgTimeCalcGST( double mjd ) {
346 double day = floor(mjd-0.5)+0.5;
347 double hr = (mjd-day)*24.0;
350 T = ((int)(mjd - 0.5) + 0.5 - J2000)/36525.0;
351 x = 24110.54841 + (8640184.812866 + (0.093104 - 6.2e-6 * T) * T) * T;
353 gst = (1.0/SIDRATE)*hr + x;
359 #if defined( HAVE_TIMEGM )
360 // ignore this function
361 #elif defined( MK_TIME_IS_GMT )
362 // ignore this function
363 #else // ! defined ( MK_TIME_IS_GMT )
365 // Fix up timezone if using ftime()
366 static long int fix_up_timezone( long int timezone_orig ) {
367 # if !defined( HAVE_GETTIMEOFDAY ) && defined( HAVE_FTIME )
368 // ftime() needs a little extra help finding the current timezone
369 struct timeb current;
371 return( current.timezone * 60 );
373 return( timezone_orig );
379 /******************************************************************
380 * The following are some functions that were included as SGTime
381 * members, although they currently don't make use of any of the
382 * class's variables. Maybe this'll change in the future
383 *****************************************************************/
385 // Return time_t for Sat Mar 21 12:00:00 GMT
387 // On many systems it is ambiguous if mktime() assumes the input is in
388 // GMT, or local timezone. To address this, a new function called
389 // timegm() is appearing. It works exactly like mktime() but
390 // explicitely interprets the input as GMT.
392 // timegm() is available and documented under FreeBSD. It is
393 // available, but completely undocumented on my current Debian 2.1
396 // In the absence of timegm() we have to guess what mktime() might do.
398 // Many older BSD style systems have a mktime() that assumes the input
399 // time in GMT. But FreeBSD explicitly states that mktime() assumes
402 // The mktime() on many SYSV style systems (such as Linux) usually
403 // returns its result assuming you have specified the input time in
404 // your local timezone. Therefore, in the absence if timegm() you
405 // have to go to extra trouble to convert back to GMT.
407 // If you are having problems with incorrectly positioned astronomical
408 // bodies, this is a really good place to start looking.
410 time_t sgTimeGetGMT(int year, int month, int day, int hour, int min, int sec)
420 mt.tm_isdst = -1; // let the system determine the proper time zone
422 // For now we assume that if daylight is not defined in
423 // /usr/include/time.h that we have a machine with a mktime() that
424 // assumes input is in GMT ... this only matters if we are
425 // building on a system that does not have timegm()
426 #if !defined(HAVE_DAYLIGHT)
427 # define MK_TIME_IS_GMT 1
430 #if defined( HAVE_TIMEGM )
431 return ( timegm(&mt) );
432 #elif defined( MK_TIME_IS_GMT )
433 time_t ret = mktime(&mt);
439 // This is necessary as some mktime() calls may
440 // try to access the system timezone files
441 // if this open fails errno is set to 2
442 // CYGWIN for one does this
444 // perror( "sgTimeGetGMT()" );
448 // reset errno in any event.
452 #else // ! defined ( MK_TIME_IS_GMT )
454 // timezone seems to work as a proper offset for Linux & Solaris
455 # if defined( __linux__ ) || defined(__sun) ||defined(__CYGWIN__)
456 # define TIMEZONE_OFFSET_WORKS 1
459 #if defined(__CYGWIN__)
460 #define TIMEZONE _timezone
462 #define TIMEZONE timezone
465 time_t start = mktime(&mt);
467 SG_LOG( SG_EVENT, SG_DEBUG, "start1 = " << start );
468 // the ctime() call can screw up time progression on some versions
470 // fgPrintf( SG_EVENT, SG_DEBUG, "start2 = %s", ctime(&start));
471 SG_LOG( SG_EVENT, SG_DEBUG, "(tm_isdst = " << mt.tm_isdst << ")" );
473 TIMEZONE = fix_up_timezone( TIMEZONE );
475 # if defined( TIMEZONE_OFFSET_WORKS )
476 SG_LOG( SG_EVENT, SG_DEBUG,
477 "start = " << start << ", timezone = " << TIMEZONE );
478 return( start - TIMEZONE );
479 # else // ! defined( TIMEZONE_OFFSET_WORKS )
481 daylight = mt.tm_isdst;
482 if ( daylight > 0 ) {
484 } else if ( daylight < 0 ) {
485 SG_LOG( SG_EVENT, SG_WARN,
486 "OOOPS, problem in sg_time.cxx, no daylight savings info." );
489 long int offset = -(TIMEZONE / 3600 - daylight);
491 SG_LOG( SG_EVENT, SG_DEBUG, " Raw time zone offset = " << TIMEZONE );
492 SG_LOG( SG_EVENT, SG_DEBUG, " Daylight Savings = " << daylight );
493 SG_LOG( SG_EVENT, SG_DEBUG, " Local hours from GMT = " << offset );
495 long int start_gmt = start - TIMEZONE + (daylight * 3600);
497 SG_LOG( SG_EVENT, SG_DEBUG, " March 21 noon (CST) = " << start );
499 return ( start_gmt );
500 # endif // ! defined( TIMEZONE_OFFSET_WORKS )
501 #endif // ! defined ( MK_TIME_IS_GMT )
506 char* sgTimeFormatTime( const struct tm* p, char* buf )
508 sprintf( buf, "%d/%d/%2d %d:%02d:%02d",
509 p->tm_mon, p->tm_mday, p->tm_year,
510 p->tm_hour, p->tm_min, p->tm_sec);