/contrib/ntp/scripts/monitoring/timelocal.pl

https://bitbucket.org/freebsd/freebsd-head/ · Perl · 77 lines · 66 code · 11 blank · 0 comment · 10 complexity · e096803a46f7e31587e8d7fb07c53e62 MD5 · raw file

  1. ;# timelocal.pl
  2. ;#
  3. ;# Usage:
  4. ;# $time = timelocal($sec,$min,$hours,$mday,$mon,$year,$junk,$junk,$isdst);
  5. ;# $time = timegm($sec,$min,$hours,$mday,$mon,$year);
  6. ;# These routines are quite efficient and yet are always guaranteed to agree
  7. ;# with localtime() and gmtime(). We manage this by caching the start times
  8. ;# of any months we've seen before. If we know the start time of the month,
  9. ;# we can always calculate any time within the month. The start times
  10. ;# themselves are guessed by successive approximation starting at the
  11. ;# current time, since most dates seen in practice are close to the
  12. ;# current date. Unlike algorithms that do a binary search (calling gmtime
  13. ;# once for each bit of the time value, resulting in 32 calls), this algorithm
  14. ;# calls it at most 6 times, and usually only once or twice. If you hit
  15. ;# the month cache, of course, it doesn't call it at all.
  16. ;# timelocal is implemented using the same cache. We just assume that we're
  17. ;# translating a GMT time, and then fudge it when we're done for the timezone
  18. ;# and daylight savings arguments. The timezone is determined by examining
  19. ;# the result of localtime(0) when the package is initialized. The daylight
  20. ;# savings offset is currently assumed to be one hour.
  21. CONFIG: {
  22. package timelocal;
  23. @epoch = localtime(0);
  24. $tzmin = $epoch[2] * 60 + $epoch[1]; # minutes east of GMT
  25. if ($tzmin > 0) {
  26. $tzmin = 24 * 60 - $tzmin; # minutes west of GMT
  27. $tzmin -= 24 * 60 if $epoch[5] == 70; # account for the date line
  28. }
  29. $SEC = 1;
  30. $MIN = 60 * $SEC;
  31. $HR = 60 * $MIN;
  32. $DAYS = 24 * $HR;
  33. $YearFix = ((gmtime(946684800))[5] == 100) ? 100 : 0;
  34. }
  35. sub timegm {
  36. package timelocal;
  37. $ym = pack(C2, @_[5,4]);
  38. $cheat = $cheat{$ym} || &cheat;
  39. $cheat + $_[0] * $SEC + $_[1] * $MIN + $_[2] * $HR + ($_[3]-1) * $DAYS;
  40. }
  41. sub timelocal {
  42. package timelocal;
  43. $ym = pack(C2, @_[5,4]);
  44. $cheat = $cheat{$ym} || &cheat;
  45. $cheat + $_[0] * $SEC + $_[1] * $MIN + $_[2] * $HR + ($_[3]-1) * $DAYS
  46. + $tzmin * $MIN - 60 * 60 * ($_[8] != 0);
  47. }
  48. package timelocal;
  49. sub cheat {
  50. $year = $_[5];
  51. $month = $_[4];
  52. $guess = $^T;
  53. @g = gmtime($guess);
  54. $year += $YearFix if $year < $epoch[5];
  55. while ($diff = $year - $g[5]) {
  56. $guess += $diff * (364 * $DAYS);
  57. @g = gmtime($guess);
  58. }
  59. while ($diff = $month - $g[4]) {
  60. $guess += $diff * (28 * $DAYS);
  61. @g = gmtime($guess);
  62. }
  63. $g[3]--;
  64. $guess -= $g[0] * $SEC + $g[1] * $MIN + $g[2] * $HR + $g[3] * $DAYS;
  65. $cheat{$ym} = $guess;
  66. }