tm2sec.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. #include <u.h>
  2. #include <libc.h>
  3. #include "zoneinfo.h"
  4. #define SEC2MIN 60L
  5. #define SEC2HOUR (60L*SEC2MIN)
  6. #define SEC2DAY (24L*SEC2HOUR)
  7. /*
  8. * days per month plus days/year
  9. */
  10. static int dmsize[] =
  11. {
  12. 365, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
  13. };
  14. static int ldmsize[] =
  15. {
  16. 366, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
  17. };
  18. /*
  19. * return the days/month for the given year
  20. */
  21. static int *
  22. yrsize(int y)
  23. {
  24. if((y%4) == 0 && ((y%100) != 0 || (y%400) == 0))
  25. return ldmsize;
  26. else
  27. return dmsize;
  28. }
  29. /*
  30. * compute seconds since Jan 1 1970 GMT
  31. * and convert to our timezone.
  32. */
  33. long
  34. tm2sec(Tm *tm)
  35. {
  36. Tinfo ti0, ti1, *ti;
  37. long secs;
  38. int i, yday, year, *d2m;
  39. secs = 0;
  40. /*
  41. * seconds per year
  42. */
  43. year = tm->year + 1900;
  44. for(i = 1970; i < year; i++){
  45. d2m = yrsize(i);
  46. secs += d2m[0] * SEC2DAY;
  47. }
  48. /*
  49. * if mday is set, use mon and mday to compute yday
  50. */
  51. if(tm->mday){
  52. yday = 0;
  53. d2m = yrsize(year);
  54. for(i=0; i<tm->mon; i++)
  55. yday += d2m[i+1];
  56. yday += tm->mday-1;
  57. }else{
  58. yday = tm->yday;
  59. }
  60. secs += yday * SEC2DAY;
  61. /*
  62. * hours, minutes, seconds
  63. */
  64. secs += tm->hour * SEC2HOUR;
  65. secs += tm->min * SEC2MIN;
  66. secs += tm->sec;
  67. /*
  68. * Assume the local time zone if zone is not GMT
  69. */
  70. if(strcmp(tm->zone, "GMT") != 0) {
  71. i = zonelookuptinfo(&ti0, secs);
  72. ti = &ti0;
  73. if (i != -1)
  74. if (ti->tzoff!=0) {
  75. /*
  76. * to what local time period `secs' belongs?
  77. */
  78. if (ti->tzoff>0) {
  79. /*
  80. * east of GMT; check previous local time transition
  81. */
  82. if (ti->t+ti->tzoff > secs)
  83. if (zonetinfo(&ti1, i-1)!=-1)
  84. ti = &ti1;
  85. } else
  86. /*
  87. * west of GMT; check next local time transition
  88. */
  89. if (zonetinfo(&ti1, i+1))
  90. if (ti1.t+ti->tzoff < secs)
  91. ti = &ti1;
  92. // fprint(2, "tt: %ld+%d %ld\n", (long)ti->t, ti->tzoff, (long)secs);
  93. secs -= ti->tzoff;
  94. }
  95. }
  96. if(secs < 0)
  97. secs = 0;
  98. return secs;
  99. }