1/*
2 * caltontp - convert a date to an NTP time
3 */
4#include <config.h>
5#include <sys/types.h>
6
7#include "ntp_types.h"
8#include "ntp_calendar.h"
9#include "ntp_stdlib.h"
10#include "ntp_assert.h"
11#include "ntp_unixtime.h"
12
13/*
14 * Juergen Perlinger, 2008-11-12
15 * Add support for full calendar calculatios. If the day-of-year is provided
16 * (that is, not zero) it will be used instead of month and day-of-month;
17 * otherwise a full turn through the calendar calculations will be taken.
18 *
19 * I know that Harlan Stenn likes to see assertions in production code, and I
20 * agree there, but it would be a tricky thing here. The algorithm is quite
21 * capable of producing sensible answers even to seemingly weird inputs: the
22 * date <any year here>-03-00, the 0.th March of the year, will be automtically
23 * treated as the last day of February, no matter whether the year is a leap
24 * year or not. So adding constraints is merely for the benefit of the callers,
25 * because the only thing we can check for consistency is our input, produced
26 * by somebody else.
27 *
28 * BTW: A total roundtrip using 'caljulian' would be a quite shaky thing:
29 * Because of the truncation of the NTP time stamp to 32 bits and the epoch
30 * unfolding around the current time done by 'caljulian' the roundtrip does
31 * *not* necessarily reproduce the input, especially if the time spec is more
32 * than 68 years off from the current time...
33 */
34
35uint32_t
36caltontp(
37	const struct calendar *jt
38	)
39{
40	int32_t eraday;	/* CE Rata Die number	*/
41	vint64  ntptime;/* resulting NTP time	*/
42
43	REQUIRE(jt != NULL);
44
45	REQUIRE(jt->month <= 13);	/* permit month 0..13! */
46	REQUIRE(jt->monthday <= 32);
47	REQUIRE(jt->yearday <= 366);
48	REQUIRE(jt->hour <= 24);
49	REQUIRE(jt->minute <= MINSPERHR);
50	REQUIRE(jt->second <= SECSPERMIN);
51
52	/*
53	 * First convert the date to he corresponding RataDie
54	 * number. If yearday is not zero, assume that it contains a
55	 * useable value and avoid all calculations involving month
56	 * and day-of-month. Do a full evaluation otherwise.
57	 */
58	if (jt->yearday)
59		eraday = ntpcal_year_to_ystart(jt->year)
60		       + jt->yearday - 1;
61	else
62		eraday = ntpcal_date_to_rd(jt);
63
64	ntptime = ntpcal_dayjoin(eraday - DAY_NTP_STARTS,
65				 ntpcal_etime_to_seconds(jt->hour, jt->minute,
66							 jt->second));
67	return ntptime.d_s.lo;
68}
69