xref: /PHP-7.4/ext/calendar/cal_unix.c (revision e857dfa7)
1 /*
2    +----------------------------------------------------------------------+
3    | PHP Version 7                                                        |
4    +----------------------------------------------------------------------+
5    | Copyright (c) The PHP Group                                          |
6    +----------------------------------------------------------------------+
7    | This source file is subject to version 3.01 of the PHP license,      |
8    | that is bundled with this package in the file LICENSE, and is        |
9    | available through the world-wide-web at the following url:           |
10    | http://www.php.net/license/3_01.txt                                  |
11    | If you did not receive a copy of the PHP license and are unable to   |
12    | obtain it through the world-wide-web, please send a note to          |
13    | license@php.net so we can mail you a copy immediately.               |
14    +----------------------------------------------------------------------+
15    | Authors: Shane Caraveo             <shane@caraveo.com>               |
16    |          Colin Viebrock            <colin@easydns.com>               |
17    |          Hartmut Holzgraefe        <hholzgra@php.net>                |
18    +----------------------------------------------------------------------+
19  */
20 
21 #include "php.h"
22 #include "php_calendar.h"
23 #include "sdncal.h"
24 #include <time.h>
25 
26 #define SECS_PER_DAY (24 * 3600)
27 
28 /* {{{ proto int unixtojd([int timestamp])
29    Convert UNIX timestamp to Julian Day */
PHP_FUNCTION(unixtojd)30 PHP_FUNCTION(unixtojd)
31 {
32 	time_t ts = 0;
33 	zend_long tl = 0;
34 	struct tm *ta, tmbuf;
35 
36 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|l", &tl) == FAILURE) {
37 		return;
38 	}
39 
40 	if (!tl) {
41 		ts = time(NULL);
42 	} else if (tl >= 0) {
43 		ts = (time_t) tl;
44 	} else {
45 		RETURN_FALSE;
46 	}
47 
48 	if (!(ta = php_localtime_r(&ts, &tmbuf))) {
49 		RETURN_FALSE;
50 	}
51 
52 	RETURN_LONG(GregorianToSdn(ta->tm_year+1900, ta->tm_mon+1, ta->tm_mday));
53 }
54 /* }}} */
55 
56 /* {{{ proto int jdtounix(int jday)
57    Convert Julian Day to UNIX timestamp */
PHP_FUNCTION(jdtounix)58 PHP_FUNCTION(jdtounix)
59 {
60 	zend_long uday;
61 
62 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &uday) == FAILURE) {
63 		return;
64 	}
65 	uday -= 2440588 /* J.D. of 1.1.1970 */;
66 
67 	if (uday < 0 || uday > ZEND_LONG_MAX / SECS_PER_DAY) { /* before beginning of unix epoch or greater than representable */
68 		RETURN_FALSE;
69 	}
70 
71 	RETURN_LONG(uday * SECS_PER_DAY);
72 }
73 /* }}} */
74