Código de PHP - Clase para el uso de fechas en PHP

Imágen de perfil
Val: 1.009
Bronce
Ha mantenido su posición en PHP (en relación al último mes)
Gráfica de PHP

Clase para el uso de fechas en PHPgráfica de visualizaciones


PHP

Publicado el 15 de Agosto del 2019 por Xavi (548 códigos)
2.035 visualizaciones desde el 15 de Agosto del 2019
Esta clase es para gestionar todas las posibles utilidades con fechas...

Permite:
- validar una fecha en formato español
- validar una fecha en formato ingles
- validar la hora, minutos y segundos
- convertir una fecha entre el formato ingles y el español
- convertir una fecha entre el formato español y el ingles
- obtener los días entre dos fechas
- validar si una fecha esta dentro del siguiente año a la fecha actual
- convertir una fecha a texto
- obtener la edad de una persona
- obtener la fecha menor de un array de fechas

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$df=new dateFunctions();
echo "<br>".$df->dateSpanishToEnglish("25/01/2019"); // 2019/01/25
echo "<br>".$df->dateEnglishToSpanish("01-25-2019"); // true
echo "<br>".$df->validateDateEs("25/01/2019"); // false
echo "<br>".$df->validateDateEs("32/01/2019"); // true
echo "<br>".$df->validateDateTimeEs("2019/25/01 10:10:10"); // true
echo "<br>".$df->validateDateTimeEs("2019/25/01 10:62:10"); // false
echo "<br>".$df->validateDateEn("2019/01/25"); // true
echo "<br>".$df->validateDateEn("2019/01/32"); // false
echo "<br>".$df->validateDateTimeEn("2019/01/25 10:10:10"); // true
echo "<br>".$df->validateDateTimeEn("2019/01/25 10:62:10"); // false
echo "<br>".$df->validateTime("10:10:10"); // true
echo "<br>".$df->validateTime("10:62:10"); // false
echo "<br>".$df->daysBetweenTwoDates("2019/01/25", "2019/02/25"); // 31
echo "<br>".$df->daysBetweenTwoDates("2019/02/25", "2019/01/25"); // -31
echo "<br>".$df->validate_dateInOneYear("25/01/2020"); // True (hoy es 15 de Agosto del 2019)
echo "<br>".$df->dateToText("2019/01/25"); // 25 de Enero del 2019
echo "<br>".$df->getYearsOld("1975/01/25"); // 44 (hoy es 18 de Agosto del 2019)
echo "<br>".$df->getMinDate(["1975/01/25", "1978/01/20", "1970/10/25"]); // 1970-10-25

Requerimientos

php 7.x

Versión 1
estrellaestrellaestrellaestrellaestrella(1)

Publicado el 15 de Agosto del 2019gráfica de visualizaciones de la versión: Versión 1
2.036 visualizaciones desde el 15 de Agosto del 2019
estrellaestrellaestrellaestrellaestrella
estrellaestrellaestrellaestrella
estrellaestrellaestrella
estrellaestrella
estrella

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
<?php
/**
 * Class dateFunctions
 *
 * Ver. 1 20190726
 *
 * clase para trabajar con fechas
 */
 
class dateFunctions
{
    public $config_meses=array(1=>"Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre");
 
    /**
     * Funcion que devuelve una fecha en formato ingles: yyyy/mm/dd
     * 
     * @param string $date - date in spanish format without time
     * 
     * @return string - date in english format or ""
     */
    public function dateSpanishToEnglish($date)
    {
        if ($date) {
            $values=preg_split('/(\/|-)/', $date);
            if (count($values)==3 && $this->validateDateEs($date)) {
                return date("Y/m/d", mktime(0, 0, 0, $values[1], $values[0], $values[2]));
            }
        }
        return "";
    }
 
    /**
     * Funcion que devuelve una fecha en formato español: dd/mm/yyyy
     * 
     * @param string  $date     - date in english format with or less time: yyyy/mm/dd, yyyy-mm-dd hh:mm:ss, ...
     * @param boolean $showTime - define if show the time
     * 
     * @return string - date in spanish format or ""
     */
    public function dateEnglishToSpanish($date, $showTime=true)
    {
        if (strtotime($date)) {
            if ($showTime) {
                return date("d/m/Y H:i:s", strtotime($date));
            }
            return date("d/m/Y", strtotime($date));
        }
        return "";
    }
 
    /**
     * Funcion para validar una fecha en formato español: dd/mm/yyyy, d/m/yyyy, d/m/yy
     * 
     * @param string $date - in spanish format: dd/mm/yyyy, d/m/yyyy, d/m/yy
     * 
     * @return boolean
     */
    public function validateDateEs($date)
    {
        $pattern="/^(0?[1-9]|[12][0-9]|3[01])[\/|-](0?[1-9]|[1][012])[\/|-]((19|20)?[0-9]{2})$/";
        if (preg_match($pattern, $date)) {
            $values=preg_split("[\/|-]", $date);
            if (checkdate($values[1], $values[0], $values[2])) {
                return true;
            }
        }
        return false;
    }
 
    /**
     * Funcion para validar una fecha y hora en formato: dd/mm/yyyy hh:mm:ss, d/m/yyyy hh:mm:ss, d/m/yy hh:mm:ss
     * 
     * @param string $dateTime - date time in format: dd/mm/yyyy hh:mm:ss, d/m/yyyy hh:mm:ss, d/m/yy hh:mm:ss
     * 
     * @return boolean
     */
    public function validateDateTimeEs($dateTime)
    {
        $valores=explode(" ", $dateTime);
        if (count($valores)==2) {
            if ($this->validateDateEs($valores[0]) && $this->validateTime($valores[1])) {
                return true;
            }
        }
        return false;
    }
 
    /**
     * Funcion para validar una fecha en formato ingles: yyyy/mm/dd, yyyy/m/d, yy/m/d
     * 
     * @param string $date - in english format: yyyy/mm/dd, yyyy/m/d, yy/m/d
     * 
     * @return boolean
     */
    public function validateDateEn($date)
    {
        $pattern="/^((19|20)?[0-9]{2})[\/|-](0?[1-9]|[1][012])[\/|-](0?[1-9]|[12][0-9]|3[01])$/";
        if (preg_match($pattern, $date)) {
            $values=preg_split("[\/|-]", $date);
            if (checkdate($values[1], $values[2], $values[1]) || $date=="2016-02-29") {
                return true;
            }
        }
        return false;
    }
 
    /**
     * Funcion para validar una fecha y hora en formato: yyyy/mm/dd hh:mm:ss, yyyy/m/d hh:mm:ss, yy/m/d hh:mm:ss
     * 
     * @param string $dateTime - date time in format: yyyy/mm/dd hh:mm:ss, yyyy/m/d hh:mm:ss, yy/m/d hh:mm:ss
     * 
     * @return boolean
     */
    public function validateDateTimeEn($dateTime)
    {
        $valores=explode(" ", $dateTime);
        if (count($valores)==2) {
            if ($this->validateDateEn($valores[0]) && $this->validateTime($valores[1])) {
                return true;
            }
        }
        return false;
    }
 
    /**
     * Funcion to check time in format: hh:mm:ss
     * 
     * @param string $time - format hh:mm:ss
     * 
     * @return boolean
     */
    public function validateTime($time)
    {
        $pattern="/^([0-1][0-9]|[2][0-3])[\:]([0-5][0-9])[\:]([0-5][0-9])$/";
        if (preg_match($pattern, $time)) {
            return true;
        }
        return false;
    }
 
    /**
     * Function to return the number of days between two dates
     * 
     * Sample:
     *  "2010-10-10","2010-10-11" return 1
     *  "2010-10-10","2010-10-09" return -1
     * 
     * @param string $date1 - date in yyyy-mm-dd format
     * @param string $date2 - date in yyyy-mm-dd format
     * 
     * @return int - diff days between $date1-date2. value can be negative.
     * 
     * Note: if date1 or date2 are error, return 0
     */
    public function daysBetweenTwoDates($date1,$date2)
    {
        if ($this->validateDateEn($date1)==false || $this->validateDateEn($date2)==false) {
            return 0;
        }
        return ((strtotime($date2)-strtotime($date1))/86400);
    }
 
    /**
     * Funcion que valida que una fecha sea correcta, y que este comprendida en un periodo máximo de un
     * año desde la fecha actual. Si es inferior a la fecha actual devuelve false
     * 
     * @param string $date - Tiene que recibir la fecha en formato español: dd/mm/yyyy
     * 
     * @return boolean - Devuelve true|false
     */
    public function validate_dateInOneYear($date)
    {
        if ($this->validateDateEs($date)) {
            # pasamos la fecha a formato ingles
            $date_Timestamp=strtotime($this->dateSpanishToEnglish($date));
            $dateMorOneYear_Timestamp=strtotime("+1 year");
 
            if ($date_Timestamp>$dateMorOneYear_Timestamp || $date_Timestamp<time()) {
                return false;
            }
            return true;
        }
        return false;
    }
 
    /**
     * Convert the date yyyy-mm-dd to "25 de marzo del 2015"
     * 
     * @param date $date
     * 
     * @return string - If $date is error, return ""
     */
    public function dateToText($date)
    {
        $timestamp=strtotime($date);
        if (!$timestamp) {
            return "";
        }
        $day=date("j", $timestamp);
        $month=date("n", $timestamp);
        $year=date("Y", $timestamp);
        return $day." de ".$this->config_meses[$month]." del ".$year;
    }
 
    /**
     * Funcion que calcula la edad de una persona en relacion a su fecha de
     * nacimiento.
     * 
     * @param date $date - Tiene que recibir la fecha de nacimiento en formato YYYY-MM-DD
     * 
     * @return int - years old or -1 if $date is incorrect
     */
    public function getYearsOld($date)
    {
        try {
            list($Y,$m,$d) = explode("-", $date);
            return( date("md") < $m.$d ? date("Y")-$Y-1 : date("Y")-$Y );
        } catch (Exception $e) {
            return -1;
        }
    }
 
    /**
     * Function that return the min date in array
     * 
     * @param array $dates - array with dates in format Y-m-d
     * 
     * @return string - min date in format Y-m-d
     */
    public function getMinDate($dates)
    {
        if (is_array($dates)==false || count($dates)==0) {
            return "";
        }
 
        $result=array_map(
            function ($el) {
                return strtotime($el);
            }, $dates
        );
 
        return date("Y-m-d", min($result));
    }
}



Comentarios sobre la versión: Versión 1 (1)

Ricardo Hernandez
30 de Agosto del 2019
estrellaestrellaestrellaestrellaestrella
Excelente, gracias por compartir.
Responder

Comentar la versión: Versión 1

Nombre
Correo (no se visualiza en la web)
Valoración
Comentarios...
CerrarCerrar
CerrarCerrar
Cerrar

Tienes que ser un usuario registrado para poder insertar imágenes, archivos y/o videos.

Puedes registrarte o validarte desde aquí.

Codigo
Negrita
Subrayado
Tachado
Cursiva
Insertar enlace
Imagen externa
Emoticon
Tabular
Centrar
Titulo
Linea
Disminuir
Aumentar
Vista preliminar
sonreir
dientes
lengua
guiño
enfadado
confundido
llorar
avergonzado
sorprendido
triste
sol
estrella
jarra
camara
taza de cafe
email
beso
bombilla
amor
mal
bien
Es necesario revisar y aceptar las políticas de privacidad

http://lwp-l.com/s5475