1 /*
2  * Copyright (c) 2012-2014 Christian Hansen <chansen@cpan.org>
3  * <https://github.com/chansen/c-dt>
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright notice, this
10  *    list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright notice,
12  *    this list of conditions and the following disclaimer in the documentation
13  *    and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
17  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
18  * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
19  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
20  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
21  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
22  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
24  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 #include "dt_core.h"
27 
28 bool
dt_leap_year(int y)29 dt_leap_year(int y) {
30     return ((y & 3) == 0 && (y % 100 != 0 || y % 400 == 0));
31 }
32 
33 int
dt_days_in_year(int y)34 dt_days_in_year(int y) {
35     return dt_leap_year(y) ? 366 : 365;
36 }
37 
38 int
dt_days_in_quarter(int y,int q)39 dt_days_in_quarter(int y, int q) {
40     static const int days_in_quarter[2][5] = {
41         { 0, 90, 91, 92, 92 },
42         { 0, 91, 91, 92, 92 }
43     };
44     if (q < 1 || q > 4)
45         return 0;
46     return days_in_quarter[dt_leap_year(y)][q];
47 }
48 
49 int
dt_days_in_month(int y,int m)50 dt_days_in_month(int y, int m) {
51     static const int days_in_month[2][13] = {
52         { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
53         { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
54     };
55     if (m < 1 || m > 12)
56         return 0;
57     return days_in_month[dt_leap_year(y)][m];
58 }
59 
60 int
dt_weeks_in_year(int year)61 dt_weeks_in_year(int year) {
62     unsigned int y, d;
63     if (year < 1)
64         year += 400 * (1 - year/400);
65     y = year - 1;
66     d = (y + y/4 - y/100 + y/400) % 7; /* Mon = 0, ... Sun = 6 */
67     return (d == 3 || (d == 2 && dt_leap_year(year))) ? 53 : 52;
68 }
69 
70