Código de PHP - Clase para convertir unidades de tiempo básicas

Imágen de perfil
Val: 2.325
Plata
Ha disminuido 1 puesto en PHP (en relación al último mes)
Gráfica de PHP

Clase para convertir unidades de tiempo básicasgráfica de visualizaciones


PHP

Publicado el 16 de Agosto del 2016 por Kip (28 códigos)
2.503 visualizaciones desde el 16 de Agosto del 2016
Una clase sencilla para transformar segundos, minutos y horas a segundos, minutos u horas segun se lo requiera.

Se debe crear el objeto y llamar a la función que traerá el tiempo transformado, especificando los parámetros.

Por ahora los parametros de las unidades de tiempo solo deben ingresarse en ingles y pueden ir en singular o plural, estos pueden ser secs o seconds (singular o plural) para segundos, mins o minutes (singular o plural) para minutos y hour o hours (singular o plural) para horas.

Pronto se harán mejoras a esta pequeña clase.

A continuación unos ejemplos de su uso.

Saludos

0.13
estrellaestrellaestrellaestrellaestrella(1)

Actualizado el 18 de Agosto del 2016 (Publicado el 16 de Agosto del 2016)gráfica de visualizaciones de la versión: 0.13
2.504 visualizaciones desde el 16 de Agosto del 2016
estrellaestrellaestrellaestrellaestrella
estrellaestrellaestrellaestrella
estrellaestrellaestrella
estrellaestrella
estrella

Version 0.13
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
<?php
// Creamos el objeto instanciando la clase Timefull en la variable
$ingreso_tiempo = new Timefull;
 
//Llamamos a la funcion, colocando los parametros correctos
echo $ingreso_tiempo->getTime('5 hour','secs');
// Resultado -> 18000 seconds
 
//Si no se especifica el parametro de la unidad a convertir, se autoasignara uno que por defecto son segundos
echo $ingreso_tiempo->getTime('1 hour');
// Resultado -> 3600 seconds
 
//Es posible colocar prefijos para las unidades de tiempo y no es preciso colocar en singular o plural los mismas, un ejemplo:
echo $ingreso_tiempo->getTime('3601 mins','hour');
// Resultado -> 60 hours 1 minute
 
//Para obtener directamente la operacion de conversion a la unidad de tiempo especificada, debera colocarse como tercer parametro el boolean 'true', aqui un ejemplo:
echo $ingreso_tiempo->getTime('3601 mins','hour',true);
// Resultado -> 60.01667 hours
 
//Si se ingresa una unidad cuyo valor no es igual o mayor al valor que definiria la siguiente unidad a esta, la funcion traera como resultado el mismo valor sin transformarse:
 
//Dado que 45 segundos no es el valor que tiene un minuto entonces la funcion traera los 45 segundos ingresados
echo $ingreso_tiempo->getTime('45 secs','minutes');
//Resultado-> 45 seconds;
 
//Si se desea obtener sin importar el valor de la unidad ingresada, el valor de la unidad a transformar, colocar como tercer parametro el boolean 'true'
echo $ingreso_tiempo->getTime('45 secs','minutes',true);
//Resultado-> 0.75000 minutes
 
// Otros ejemplos
 
echo $ingreso_tiempo->getTime('4564 seconds','hours');
// Resultado -> 1 hour 16 minutes 4 seconds
 
//Recordar que los parametros a ingresar como unidades de tiempo deben ser en ingles y estos pueden ser secs o seconds (singular o plural) para segundos, mins o minutes (singular o plural) para minutos y hour o hours (singular o plural) para horas.
 
/************************************************************************************************

CODIGO FUENTE DE LA CLASE

*************************************************************************************************/
 
class Timefull
{
 
	public $def_return = ['s'=>'second','m'=>'minute','h'=>'hour','seconds','minutes','hours','min','sec','mins','secs'];
	public $def_time;
	public $def_transform;
	public $time;
	public $seconds;
	public $minutes;
	public $hours;
	public $error;
	private $raw;
 
       public function getTime($time = null,$def_transform = null,$raw = false){
		$this->raw = ($raw) ? true : false ;
		if ($time != null){
			$this->time = trim($time);
			return $this->evaluateTime($def_transform);
		}
	}
 
	public function evaluateTime($def_transform){
		if ($this->time){
			$split = str_split($this->time);
			$this->time = null;
			for ($i=0,$s=count($split); $i<$s;$i++){
				if( is_numeric($split[$i])){
					$this->time .= $split[$i];
				} else if (($split[$i] == ',') || ($split[$i] == '.')) {
					$this->time .= str_replace(',','.',$split[$i]);
				} else {
					break;
				}
			}
			$this->def_time = substr(implode('',$split),$i);
			return $this->transformTime($def_transform);
		}
	}
 
	public function transformTime($def_transform){
		if($def_transform){
			$def_transform = (in_array($def_transform,$this->def_return)) ? $def_transform : $this->autoDef(true) ;
		} else {
			$def_transform = $this->autoDef();
		}
		if ($this->error) { return $this->error; exit; }
		$this->def_transform = $def_transform;
		$time_transform = $this->evaluateTransform();
		if(is_array($time_transform['time'])){
			for ($i=0,$s=count($time_transform['time']); $i<$s;$i++) {
				$return[] = ($time_transform['time'][$i] > 1) ? "{$time_transform['time'][$i]} {$time_transform['def'][$i]}s " : "{$time_transform['time'][$i]} {$time_transform['def'][$i]} " ;
			}
			return implode('',$return);
		} else {
			if ($time_transform['time'] > 1 || $time_transform['time'] > 0.1){
				return "{$time_transform['time']} {$time_transform['def']}s";
			} else {
				return "{$time_transform['time']} {$time_transform['def']}";
			}
		}
	}
 
	public function evaluateTransform(){
		if (preg_match("/\bsec(s?|ond(s?))?\b/i",$this->def_time)) { return $this->seconds(); }
		if (preg_match("/\bmin(s?|ute(s?))?\b/i",$this->def_time)) { return $this->minutes(); }
		if (preg_match("/\bhour(s?)\b/i",$this->def_time)) { return $this->hours(); }
	}
 
	public function seconds($retry = false){
		if ((preg_match("/\bsec(s?|ond(s?))?\b/i",$this->def_transform)) || $retry){
			$this->seconds = $this->time;
			return ['time'=>$this->seconds,'def'=>$this->def_return['s']];
		} else {
			if(preg_match("/\bmin(s?|ute(s?))?\b/i",$this->def_transform)) return $this->secondsMinutes();
			if(preg_match("/\bhour(s?)\b/i",$this->def_transform)) return $this->secondsHours();
		}
	}
 
	public function minutes($retry = false){
		if ((preg_match("/\bmin(s?|ute(s?))?\b/i",$this->def_transform)) || $retry){
			$this->minutes = $this->time;
			return ['time'=>$this->minutes,'def'=>$this->def_return['m']];
		} else {
			if(preg_match("/\bsec(s?|ond(s?))?\b/i",$this->def_transform)) return $this->minutesSeconds();
			if(preg_match("/\bhour(s?)\b/i",$this->def_transform)) return $this->minutesHours();
		}
	}
 
	public function hours(){
		if (preg_match("/\bhour(s?)\b/i",$this->def_transform)){
			$this->hours = $this->time;
			return ['time'=>$this->hours,'def'=>$this->def_return['h']];
		} else {
			if(preg_match("/\bsec(s?|ond(s?))?\b/i",$this->def_transform)) return $this->hoursSeconds();
			if(preg_match("/\bmin(s?|ute(s?))?\b/i",$this->def_transform)) return $this->hoursMinutes();
		}
	}
 
	public function secondsMinutes(){
		$time = $this->time;
		if(!$this->raw){
			if ($time > 59){
				$this->minutes = (int)floor($time/60);
				$this->seconds = (int)$time-($this->minutes*60);
				if ($this->seconds == 0){
					return ['time'=>$this->minutes,$this->def_return['m']];
				} else {
					return ['time'=>[$this->minutes,$this->seconds],'def'=>[$this->def_return['m'],$this->def_return['s']]];
				}
			} else {
				return $this->seconds(true);
			}
		} else {
			$this->minutes = number_format($time/60,5,'.','');
			if (substr(strstr($this->minutes,'.'),1) == 0) {
				$this->minutes = (int)floor($time/60);
				return ['time'=>$this->minutes,'def'=>$this->def_return['m']];
			} else {
				return ['time'=>$this->minutes,'def'=>$this->def_return['m']];
			}
		}
	}
 
	public function secondsHours(){
		$time = $this->time;
		if(!$this->raw){
			if ($time > 59 && $time < 3600){
			return $this->secondsMinutes();
			} else if ($time > 3599){
				$this->hours = (int)floor($time/3600);
				$this->minutes = (int)floor(($time-($this->hours*3600))/60);
				$this->seconds = (int)(($time-($this->hours*3600))-($this->minutes*60));
				if($this->minutes == 0 && $this->seconds == 0){
					return ['time'=>$this->hours,'def'=> $this->def_return['h']];
				} else if ($this->minutes != 0 && $this->seconds == 0) {
					return ['time'=>[$this->hours,$this->minutes],'def'=> [$this->def_return['h'],$this->def_return['m']]];
				} else if ($this->minutes == 0 && $this->seconds != 0) {
					return ['time'=>[$this->hours,$this->seconds],'def'=> [$this->def_return['h'],$this->def_return['s']]];
				} else {
					return ['time'=>[$this->hours,$this->minutes,$this->seconds],'def'=> [$this->def_return['h'],$this->def_return['m'],$this->def_return['s']]];
				}
			} else {
				return $this->seconds(true);
			}
		} else {
			$this->hours = number_format($time/3600,5,'.','');
			if (substr(strstr($this->hours,'.'),1) == 0) {
				$this->hours = (int)floor($time/3600);
				return ['time'=>$this->hours,'def'=>$this->def_return['h']];
			} else {
				return ['time'=>$this->hours,'def'=>$this->def_return['h']];
			}
		}
	}
 
	public function minutesSeconds(){
		$time = $this->time;
		if (!$this->raw){
			$this->seconds = (int)($time*60);
			return ['time'=>$this->seconds,'def'=>$this->def_return['s']];
		} else {
			$this->seconds = ($time*60);
			return ['time'=>$this->seconds,'def'=>$this->def_return['s']];
		}
	}
 
	public function minutesHours(){
		$time=$this->time;
		if(!$this->raw){
			if ($time > 59) {
				$this->hours = (int)floor($time/60);
				$this->minutes = (int)floor($time-($this->hours*60));
				if($this->minutes == 0){
					return ['time'=>$this->hours,'def'=>$this->def_return['h']];
				} else {
					return ['time'=>[$this->hours,$this->minutes],'def'=>[$this->def_return['h'],$this->def_return['m']]];
				}
			} else {
				return $this->minutes(true);
			}
		} else {
			$this->hours = number_format($time/60,5,'.','');
			if (substr(strstr($this->hours,'.'),1) == 0) {
				$this->hours = (int)floor($time/60);
				return ['time'=>$this->hours,'def'=>$this->def_return['h']];
			} else {
				return ['time'=>$this->hours,'def'=>$this->def_return['h']];
			}
		}
	}
 
	public function hoursSeconds(){
		$time = $this->time;
		if(!$this->raw){
			$this->seconds = (int)($time*3600);
			return ['time'=>$this->seconds,'def'=>$this->def_return['s']];
		} else {
			$this->seconds = ($time*3600);
			return ['time'=>$this->seconds,'def'=>$this->def_return['s']];
		}
	}
 
	public function hoursMinutes(){
		$time = $this->time;
		if(!$this->raw){
			$this->minutes = (int)($time*60);
			return ['time'=>$this->minutes,'def'=>$this->def_return['m']];
		} else {
			$this->minutes = ($time*60);
			return ['time'=>$this->minutes,'def'=>$this->def_return['m']];
		}
	}
 
	public function autoDef($error = false){
		if ($error) {
			$this->error = 'IS NOT A CORRECT VALUE TO TRANSFORM!';
		} else {
			return 'seconds';
		}
	}
 
}



Comentarios sobre la versión: 0.13 (1)

Imágen de perfil
16 de Agosto del 2016
estrellaestrellaestrellaestrellaestrella
Excelente Kip!!!!
Responder

Comentar la versión: 0.13

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/s3635