Passed
Push — master ( 3b5a7c...0f24e7 )
by Jean-Christophe
05:29
created

UDateTime::mysqlDate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 2
ccs 0
cts 2
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Ubiquity\utils\base;
4
5
class UDateTime {
6
	const MYSQL_DATETIME_FORMAT='Y-m-d H:i:s';
7
	const MYSQL_DATE_FORMAT='Y-m-d';
8
	
9
	private static $locales=["fr"=>["fr","fr_FR","fr_FR.ISO8859-1"],"en"=>["en","en_US","en_US.UTF-8"]];
10
	
11 1
	private static function setLocale($locale){
12 1
		if(isset(self::$locales[$locale])){
13 1
			$locale= self::$locales[$locale];
14
		}else{
15
			$locale=self::$locales["en"];
16
		}
17 1
		setlocale(LC_TIME, $locale[0],$locale[1],$locale[2]);
18 1
	}
19
	public static function secondsToTime($seconds){
20
		$hours = floor($seconds / 3600);
21
		$mins = floor($seconds / 60 % 60);
22
		$secs = floor($seconds % 60);
23
		return sprintf('%02d:%02d:%02d', $hours, $mins, $secs);
24
	}
25
	
26
	public static function mysqlDate(\DateTime $date){
27
		return $date->format(self::MYSQL_DATE_FORMAT);
28
	}
29
	
30
	public static function mysqlDateTime(\DateTime $datetime){
31
		return $datetime->format(self::MYSQL_DATETIME_FORMAT);
32
	}
33
	
34
	public static function longDate($date,$locale="en"){
35
		self::setLocale($locale);
36
		return strftime("%A %d %B %Y",strtotime($date));
37
	}
38
	
39
	public static function shortDate($date,$locale="en"){
40
		self::setLocale($locale);
41
		return strftime("%AD",strtotime($date));
42
	}
43
	
44
	public static function shortDatetime($datetime,$locale="en"){
45
		self::setLocale($locale);
46
		return strftime("%c",strtotime($datetime));
47
	}
48
	
49 1
	public static function longDatetime($datetime,$locale="en"){
50 1
		self::setLocale($locale);
51 1
		return strftime("%A %d %B %Y, %T",strtotime($datetime));
52
	}
53
	
54
	/**
55
	 * @param string $datetime
56
	 * @param boolean $full
57
	 * @return string
58
	 * @see http://stackoverflow.com/questions/1416697/converting-timestamp-to-time-ago-in-php-e-g-1-day-ago-2-days-ago
59
	 */
60 1
	public static function elapsed($datetime, $full = false) {
61 1
		$now = new \DateTime();
62 1
		$ago = new \DateTime($datetime);
63 1
		$diff = $now->diff($ago);
64
		
65 1
		$diff->w = floor($diff->d / 7);
66 1
		$diff->d -= $diff->w * 7;
67
		
68
		$string = array(
69 1
				'y' => 'year',
70
				'm' => 'month',
71
				'w' => 'week',
72
				'd' => 'day',
73
				'h' => 'hour',
74
				'i' => 'minute',
75
				's' => 'second',
76
		);
77 1
		foreach ($string as $k => &$v) {
78 1
			if ($diff->$k) {
79 1
				$v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
80
			} else {
81 1
				unset($string[$k]);
82
			}
83
		}
84
		
85 1
		if (!$full) $string = array_slice($string, 0, 1);
86 1
		return $string ? implode(', ', $string) . ' ago' : 'just now';
87
	}
88
}
89
90