xref: /netbsd-src/external/bsd/ntp/dist/libntp/calyearstart.c (revision cdfa2a7ef92791ba9db70a584a1d904730e6fb46)
1 /*	$NetBSD: calyearstart.c,v 1.5 2020/05/25 20:47:24 christos Exp $	*/
2 
3 /*
4  * calyearstart - determine the NTP time at midnight of January 1 in
5  *		  the year of the given date.
6  */
7 #include <config.h>
8 #include <sys/types.h>
9 
10 #include "ntp_types.h"
11 #include "ntp_calendar.h"
12 #include "ntp_stdlib.h"
13 #include "ntp_assert.h"
14 
15 /*
16  * Juergen Perlinger, 2010-05-02
17  *
18  * Redone in terms of the calendar functions. It's rather simple:
19  * - expand the NTP time stamp
20  * - split into days and seconds since midnight, dropping the partial day
21  * - get full number of days before year start in NTP epoch
22  * - convert to seconds, truncated to 32 bits.
23  */
24 u_int32
calyearstart(u_int32 ntptime,const time_t * pivot)25 calyearstart(u_int32 ntptime, const time_t *pivot)
26 {
27 	u_int32      ndays; /* elapsed days since NTP starts */
28 	vint64       vlong;
29 	ntpcal_split split;
30 
31 	vlong = ntpcal_ntp_to_ntp(ntptime, pivot);
32 	split = ntpcal_daysplit(&vlong);
33 	ndays = ntpcal_rd_to_ystart(split.hi + DAY_NTP_STARTS)
34 	      - DAY_NTP_STARTS;
35 
36 	return (u_int32)(ndays * SECSPERDAY);
37 }
38 
39 /*
40  * calmonthstart - get NTP time at midnight of the first day of the
41  * current month.
42  */
43 u_int32
calmonthstart(u_int32 ntptime,const time_t * pivot)44 calmonthstart(u_int32 ntptime, const time_t *pivot)
45 {
46 	u_int32      ndays; /* elapsed days since NTP starts */
47 	vint64       vlong;
48 	ntpcal_split split;
49 
50 	vlong = ntpcal_ntp_to_ntp(ntptime, pivot);
51 	split = ntpcal_daysplit(&vlong);
52 	ndays = ntpcal_rd_to_mstart(split.hi + DAY_NTP_STARTS)
53 	      - DAY_NTP_STARTS;
54 
55 	return (u_int32)(ndays * SECSPERDAY);
56 }
57 
58 /*
59  * calweekstart - get NTP time at midnight of the last Monday on or
60  * before the current date.
61  */
62 u_int32
calweekstart(u_int32 ntptime,const time_t * pivot)63 calweekstart(u_int32 ntptime, const time_t *pivot)
64 {
65 	u_int32      ndays; /* elapsed days since NTP starts */
66 	vint64       vlong;
67 	ntpcal_split split;
68 
69 	vlong = ntpcal_ntp_to_ntp(ntptime, pivot);
70 	split = ntpcal_daysplit(&vlong);
71 	ndays = ntpcal_weekday_le(split.hi + DAY_NTP_STARTS, CAL_MONDAY)
72 	      - DAY_NTP_STARTS;
73 
74 	return (u_int32)(ndays * SECSPERDAY);
75 }
76 
77 /*
78  * caldaystart - get NTP time at midnight of the current day.
79  */
80 u_int32
caldaystart(u_int32 ntptime,const time_t * pivot)81 caldaystart(u_int32 ntptime, const time_t *pivot)
82 {
83 	vint64       vlong;
84 	ntpcal_split split;
85 
86 	vlong = ntpcal_ntp_to_ntp(ntptime, pivot);
87 	split = ntpcal_daysplit(&vlong);
88 
89 	return ntptime - split.lo;
90 }
91