DateClass.php
2.2 KB
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
<?php
/** @class DateClass
* $Id: DateClass.php 1131 2012-12-18 16:49:40Z elena $
* @brief extends DateTime class with createFromFormat for php 5.2
*/
class DateClass extends DateTime {
public function getTimestamp(){
return $this->format ("U");
}
/**
* This function calculates the number of days between the first and the second date. Arguments must be subclasses of DateTime
**/
static function differenceInDays ($firstDate, $secondDate){
$firstDateTimeStamp = $firstDate->format("U");
$secondDateTimeStamp = $secondDate->format("U");
$rv = round ((($firstDateTimeStamp - $secondDateTimeStamp))/86400);
return $rv;
}
/**
* This function returns an object of DateClass from $time in format $format. See date() for possible values for $format
**/
static function createFromFormat ($format, $time){
assert ($format!="");
if($time==""){
return new DateClass();
}
$regexpArray['Y'] = "(?P<Y>[12][90]\d\d)";
$regexpArray['m'] = "(?P<m>0[1-9]|1[012])";
$regexpArray['d'] = "(?P<d>0[1-9]|[12][0-9]|3[01])";
$regexpArray['-'] = "[-]";
$regexpArray['.'] = "[\. /.]";
$regexpArray[':'] = "[:]";
$regexpArray['/'] = "[\/]";
$regexpArray['space'] = "[\s]";
$regexpArray['H'] = "(?P<H>0[0-9]|1[0-9]|2[0-3])";
$regexpArray['i'] = "(?P<i>[0-5][0-9])";
$regexpArray['s'] = "(?P<s>[0-5][0-9])";
$formatArray = str_split ($format);
$regex = "";
// create the regular expression
foreach($formatArray as $character){
if ($character==" ") $regex = $regex.$regexpArray['space'];
elseif (array_key_exists($character, $regexpArray)) $regex = $regex.$regexpArray[$character];
}
$regex = "/".$regex."/";
// get results for regualar expression
preg_match ($regex, $time, $result);
// create the init string for the new DateTime
$initString = $result['Y']."-".$result['m']."-".$result['d'];
// if no value for hours, minutes and seconds was found add 00:00:00
if (isset($result['H'])) $initString = $initString." ".$result['H'].":".$result['i'].":".$result['s'];
else {$initString = $initString." 00:00:00";}
$newDate = new DateClass ($initString);
return $newDate;
}
}
?>