]> git.notmuchmail.org Git - notmuch/blob - compat/timegm.c
Merge branch 'release'
[notmuch] / compat / timegm.c
1 /* timegm.c --- Implementation of replacement timegm function.
2  *
3  * This program is free software; you can redistribute it and/or
4  * modify it under the terms of the GNU General Public License as
5  * published by the Free Software Foundation; either version 3, or (at
6  * your option) any later version.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License
14  * along with this program; if not, write to the Free Software
15  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
16  * 02110-1301, USA.  */
17
18 /* Copyright 2013 Blake Jones. */
19
20 #include <time.h>
21 #include "compat.h"
22
23 static int
24 leapyear (int year)
25 {
26     return ((year % 4) == 0 && ((year % 100) != 0 || (year % 400) == 0));
27 }
28
29 /*
30  * This is a simple implementation of timegm() which does what is needed
31  * by create_output() -- just turns the "struct tm" into a GMT time_t.
32  * It does not normalize any of the fields of the "struct tm", nor does
33  * it set tm_wday or tm_yday.
34  */
35 time_t
36 timegm (struct tm *tm)
37 {
38     int monthlen[2][12] = {
39         { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
40         { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
41     };
42     int year, month, days;
43
44     days = 365 * (tm->tm_year - 70);
45     for (year = 70; year < tm->tm_year; year++) {
46         if (leapyear (1900 + year)) {
47             days++;
48         }
49     }
50     for (month = 0; month < tm->tm_mon; month++) {
51         days += monthlen[leapyear (1900 + year)][month];
52     }
53     days += tm->tm_mday - 1;
54
55     return ((((days * 24) + tm->tm_hour) * 60 + tm->tm_min) * 60 + tm->tm_sec);
56 }