DateHelper.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. <?php
  2. class Application_Common_DateHelper
  3. {
  4. private $_dateTime;
  5. function __construct()
  6. {
  7. $this->_dateTime = date("U");
  8. }
  9. /**
  10. * Get time of object construction in the format
  11. * YYYY-MM-DD HH:mm:ss
  12. */
  13. function getTimestamp()
  14. {
  15. return date("Y-m-d H:i:s", $this->_dateTime);
  16. }
  17. /**
  18. * Get time of object construction in the format
  19. * YYYY-MM-DD HH:mm:ss
  20. */
  21. function getUtcTimestamp()
  22. {
  23. return gmdate("Y-m-d H:i:s", $this->_dateTime);
  24. }
  25. /**
  26. * Get date of object construction in the format
  27. * YYYY-MM-DD
  28. */
  29. function getDate()
  30. {
  31. return gmdate("Y-m-d", $this->_dateTime);
  32. }
  33. /**
  34. * Get time of object construction in the format
  35. * HH:mm:ss
  36. */
  37. function getTime()
  38. {
  39. return gmdate("H:i:s", $this->_dateTime);
  40. }
  41. /** Get the abbreviated timezone for the currently logged in user.
  42. * @return A string containing the short form of the timezone set in the preferences for the current user (eg. EST, CEST, etc.)
  43. */
  44. public static function getUserTimezoneAbbreviation()
  45. {
  46. return self::getTimezoneAbbreviation(Application_Model_Preference::GetUserTimezone());
  47. }
  48. /** Get the abbreviated timezone string of the timezone the station is set to.
  49. * @return A string containing the short form of the station's timezone (eg. EST, CEST, etc.)
  50. */
  51. public static function getStationTimezoneAbbreviation()
  52. {
  53. return self::getTimezoneAbbreviation(Application_Model_Preference::GetDefaultTimezone());
  54. }
  55. private static function getTimezoneAbbreviation($fullTimeZoneName)
  56. {
  57. $timeZone = new DateTimeZone($fullTimeZoneName);
  58. $now = new DateTime("now", $timeZone);
  59. return $now->format("T");
  60. }
  61. public static function getUserTimezoneOffset()
  62. {
  63. $userTimezone = new DateTimeZone(Application_Model_Preference::GetUserTimezone());
  64. $now = new DateTime("now", $userTimezone);
  65. return $now->format("Z");
  66. }
  67. public static function getStationTimezoneOffset()
  68. {
  69. $stationTimezone = new DateTimeZone(Application_Model_Preference::GetDefaultTimezone());
  70. $now = new DateTime("now", $stationTimezone);
  71. return $now->format("Z");
  72. }
  73. /**
  74. *
  75. * @return DateTime - YYYY-MM-DD 00:00 in station timezone of today
  76. */
  77. public static function getTodayStationStartDateTime()
  78. {
  79. $stationTimezone = new DateTimeZone(Application_Model_Preference::GetDefaultTimezone());
  80. $now = new DateTime("now", $stationTimezone);
  81. $now->setTime(0, 0, 0);
  82. return $now;
  83. }
  84. /**
  85. *
  86. * @return DateTime - YYYY-MM-DD 00:00 in station timezone of tomorrow
  87. */
  88. public static function getTodayStationEndDateTime()
  89. {
  90. $stationTimezone = new DateTimeZone(Application_Model_Preference::GetDefaultTimezone());
  91. $now = new DateTime("now", $stationTimezone);
  92. $now->add(new DateInterval("P1D"));
  93. $now->setTime(0, 0, 0);
  94. return $now;
  95. }
  96. /**
  97. *
  98. * @return DateTime - YYYY-MM-DD 00:00 in station timezone
  99. */
  100. public static function getWeekStartDateTime()
  101. {
  102. $now = self::getTodayStationStartDateTime();
  103. // our week starts on monday, but php week starts on sunday.
  104. $day = $now->format('w');
  105. if ($day == 0) {
  106. $day = 7;
  107. }
  108. $dayDiff = $day - 1;
  109. if ($dayDiff > 0) {
  110. $now->sub(new DateInterval("P{$dayDiff}D"));
  111. }
  112. return $now;
  113. }
  114. /**
  115. * This function formats a time by removing seconds
  116. *
  117. * When we receive a time from the database we get the
  118. * format "hh:mm:ss". But when dealing with show times, we
  119. * do not care about the seconds.
  120. *
  121. * @param int $p_dateTime
  122. * The value which to format.
  123. * @return int
  124. * The timestamp with the new format "hh:mm", or
  125. * the original input parameter, if it does not have
  126. * the correct format.
  127. */
  128. public static function removeSecondsFromTime($p_dateTime)
  129. {
  130. //Format is in hh:mm:ss. We want hh:mm
  131. $timeExplode = explode(":", $p_dateTime);
  132. if (count($timeExplode) == 3)
  133. return $timeExplode[0].":".$timeExplode[1];
  134. else
  135. return $p_dateTime;
  136. }
  137. /* Given a track length in the format HH:MM:SS.mm, we want to
  138. * convert this to seconds. This is useful for Liquidsoap which
  139. * likes input parameters give in seconds.
  140. * For example, 00:06:31.444, should be converted to 391.444 seconds
  141. * @param int $p_time
  142. * The time interval in format HH:MM:SS.mm we wish to
  143. * convert to seconds.
  144. * @return float
  145. * The input parameter converted to seconds.
  146. */
  147. public static function calculateLengthInSeconds($p_time){
  148. if (2 !== substr_count($p_time, ":")){
  149. return false;
  150. }
  151. if (1 === substr_count($p_time, ".")){
  152. list($hhmmss, $ms) = explode(".", $p_time);
  153. } else {
  154. $hhmmss = $p_time;
  155. $ms = 0;
  156. }
  157. list($hours, $minutes, $seconds) = explode(":", $hhmmss);
  158. $totalSeconds = ($hours*3600 + $minutes*60 + $seconds).".$ms";
  159. return round($totalSeconds, 3);
  160. }
  161. /**
  162. * returns true or false depending on input is wether in
  163. * valid range of SQL date/time
  164. * @param string $p_datetime
  165. * should be in format of '0000-00-00 00:00:00'
  166. */
  167. public static function checkDateTimeRangeForSQL($p_datetime){
  168. $info = explode(' ', $p_datetime);
  169. $dateInfo = explode('-', $info[0]);
  170. if (isset($info[1])) {
  171. $timeInfo = explode(':', $info[1]);
  172. }
  173. $retVal = array();
  174. $retVal["success"] = true;
  175. $year = $dateInfo[0];
  176. $month = $dateInfo[1];
  177. $day = $dateInfo[2];
  178. // if year is < 1753 or > 9999 it's out of range
  179. if ($year < 1753) {
  180. $retVal['success'] = false;
  181. $retVal['errMsg'] = sprintf(_("The year %s must be within the range of 1753 - 9999"), $year);
  182. } else if (!checkdate($month, $day, $year)) {
  183. $retVal['success'] = false;
  184. $retVal['errMsg'] = sprintf(_("%s-%s-%s is not a valid date"), $year, $month, $day);
  185. } else {
  186. // check time
  187. if (isset($timeInfo)) {
  188. if (isset($timeInfo[0]) && $timeInfo[0] != "") {
  189. $hour = intval($timeInfo[0]);
  190. } else {
  191. $hour = -1;
  192. }
  193. if (isset($timeInfo[1]) && $timeInfo[1] != "") {
  194. $min = intval($timeInfo[1]);
  195. } else {
  196. $min = -1;
  197. }
  198. if (isset($timeInfo[2]) && $timeInfo[2] != "") {
  199. $sec = intval($timeInfo[2]);
  200. } else {
  201. $sec = -1;
  202. }
  203. if ( ($hour < 0 || $hour > 23) || ($min < 0 || $min > 59) || ($sec < 0 || $sec > 59) ) {
  204. $retVal['success'] = false;
  205. $retVal['errMsg'] = sprintf(_("%s:%s:%s is not a valid time"), $timeInfo[0], $timeInfo[1] ,$timeInfo[2]);
  206. }
  207. }
  208. }
  209. return $retVal;
  210. }
  211. /*
  212. * @param $datetime string Y-m-d H:i:s in UTC timezone
  213. *
  214. * @return string in $format default Y-m-d H:i:s in station timezone
  215. */
  216. public static function UTCStringToStationTimezoneString($datetime, $format="Y-m-d H:i:s") {
  217. $stationTimezone = new DateTimeZone(Application_Model_Preference::GetDefaultTimezone());
  218. $utcTimezone = new DateTimeZone("UTC");
  219. $d = new DateTime($datetime, $utcTimezone);
  220. $d->setTimezone($stationTimezone);
  221. return $d->format($format);
  222. }
  223. /*
  224. * @param $datetime string Y-m-d H:i:s in UTC timezone
  225. *
  226. * @return string Y-m-d H:i:s in user's timezone
  227. */
  228. public static function UTCStringToUserTimezoneString($datetime, $format="Y-m-d H:i:s") {
  229. $userTimezone = new DateTimeZone(Application_Model_Preference::GetUserTimezone());
  230. $utcTimezone = new DateTimeZone("UTC");
  231. $d = new DateTime($datetime, $utcTimezone);
  232. $d->setTimezone($userTimezone);
  233. return $d->format($format);
  234. }
  235. /*
  236. * @param $datetime string Y-m-d H:i:s in user timezone
  237. *
  238. * @return string Y-m-d H:i:s in UTC timezone
  239. */
  240. public static function UserTimezoneStringToUTCString($datetime, $format="Y-m-d H:i:s") {
  241. $userTimezone = new DateTimeZone(Application_Model_Preference::GetUserTimezone());
  242. $utcTimezone = new DateTimeZone("UTC");
  243. $d = new DateTime($datetime, $userTimezone);
  244. $d->setTimezone($utcTimezone);
  245. return $d->format($format);
  246. }
  247. /**
  248. * Convert the columns given in the array $columnsToConvert in the
  249. * database result $rows to local timezone.
  250. *
  251. * @param array $rows arrays of arrays containing database query result
  252. * @param array $columnsToConvert array of column names to convert
  253. * @param string (station|user) convert to either station or user timezone.
  254. */
  255. public static function convertTimestamps(&$rows, $columnsToConvert, $domain="station")
  256. {
  257. if (!is_array($rows)) {
  258. return;
  259. }
  260. $converter = "UTCStringTo".ucfirst($domain)."TimezoneString";
  261. foreach ($rows as &$row) {
  262. foreach ($columnsToConvert as $column) {
  263. $row[$column] = self::$converter($row[$column]);
  264. }
  265. }
  266. }
  267. /**
  268. * Convert the columns given in the array $columnsToConvert in the
  269. * database result $rows to local timezone.
  270. *
  271. * @param array $rows arrays of arrays containing database query result
  272. * @param array $columnsToConvert array of column names to convert
  273. * @param string $timezone convert to the given timezone.
  274. * @param string $format time format to convert to
  275. */
  276. public static function convertTimestampsToTimezone(&$rows, $columnsToConvert, $timezone, $format="Y-m-d H:i:s")
  277. {
  278. $timezone = strtolower($timezone);
  279. // Check that the timezone is valid and rows is an array
  280. if (!is_array($rows)) {
  281. return;
  282. }
  283. foreach ($rows as &$row) {
  284. if (is_array($row)) {
  285. foreach ($columnsToConvert as $column) {
  286. if (array_key_exists($column, $row)) {
  287. $newTimezone = new DateTimeZone($timezone);
  288. $utcTimezone = new DateTimeZone("UTC");
  289. $d = new DateTime($row[$column], $utcTimezone);
  290. $d->setTimezone($newTimezone);
  291. $row[$column] = $d->format($format);
  292. }
  293. }
  294. self::convertTimestampsToTimezone($row, $columnsToConvert, $timezone, $format);
  295. }
  296. }
  297. }
  298. /**
  299. * Return the end date time in the given timezone
  300. *
  301. * @return DateTime
  302. */
  303. public static function getEndDateTime($timezoneString, $days)
  304. {
  305. $timezone = new DateTimeZone($timezoneString);
  306. $now = new DateTime("now", $timezone);
  307. $now->add(new DateInterval("P".$days."D"));
  308. $now->setTime(0, 0, 0);
  309. return $now;
  310. }
  311. /**
  312. * Return a formatted string representing the
  313. * given datetime in the given timezone
  314. *
  315. * @param unknown $datetime the time to convert
  316. * @param unknown $timezone the timezone to convert to
  317. * @param string $format the formatted string
  318. */
  319. public static function UTCStringToTimezoneString($datetime, $timezone, $format="Y-m-d H:i:s") {
  320. $d = new DateTime($datetime, new DateTimeZone("UTC"));
  321. $timezone = strtolower($timezone);
  322. $newTimezone = new DateTimeZone($timezone);
  323. $d->setTimezone($newTimezone);
  324. return $d->format($format);
  325. }
  326. /**
  327. * Return the timezone offset in seconds for the given timezone
  328. *
  329. * @param unknown $userDefinedTimezone the timezone used to determine the offset
  330. */
  331. public static function getTimezoneOffset($userDefinedTimezone) {
  332. $now = new DateTimeZone($userDefinedTimezone);
  333. $d = new DateTime("now", $now);
  334. return $d->format("Z");
  335. }
  336. /**
  337. * This function is used for calculations! Don't modify for display purposes!
  338. *
  339. * Convert playlist time value to float seconds
  340. *
  341. * @param string $plt
  342. * playlist interval value (HH:mm:ss.dddddd)
  343. * @return int
  344. * seconds
  345. */
  346. public static function playlistTimeToSeconds($plt)
  347. {
  348. $arr = preg_split('/:/', $plt);
  349. if (isset($arr[2])) {
  350. return (intval($arr[0])*60 + intval($arr[1]))*60 + floatval($arr[2]);
  351. }
  352. if (isset($arr[1])) {
  353. return intval($arr[0])*60 + floatval($arr[1]);
  354. }
  355. return floatval($arr[0]);
  356. }
  357. /**
  358. * This function is used for calculations! Don't modify for display purposes!
  359. *
  360. * Convert float seconds value to playlist time format
  361. *
  362. * @param float $seconds
  363. * @return string
  364. * interval in playlist time format (HH:mm:ss.d)
  365. */
  366. public static function secondsToPlaylistTime($p_seconds)
  367. {
  368. $info = explode('.', $p_seconds);
  369. $seconds = $info[0];
  370. if (!isset($info[1])) {
  371. $milliStr = 0;
  372. } else {
  373. $milliStr = $info[1];
  374. }
  375. $hours = floor($seconds / 3600);
  376. $seconds -= $hours * 3600;
  377. $minutes = floor($seconds / 60);
  378. $seconds -= $minutes * 60;
  379. $res = sprintf("%02d:%02d:%02d.%s", $hours, $minutes, $seconds, $milliStr);
  380. return $res;
  381. }
  382. /**
  383. * Returns date fields from give start and end teimstamp strings
  384. * if no start or end parameter is passed start will be set to 1
  385. * in the past and end to now
  386. *
  387. * @param string startTimestamp Y-m-d H:i:s
  388. * @param string endTImestamp Y-m-d H:i:s
  389. * @param string timezone (ex UTC) of the start and end parameters
  390. * @return array (start DateTime, end DateTime) in UTC timezone
  391. */
  392. public static function getStartEnd($startTimestamp, $endTimestamp, $timezone)
  393. {
  394. $prefTimezone = Application_Model_Preference::GetTimezone();
  395. $utcTimezone = new DateTimeZone("UTC");
  396. $utcNow = new DateTime("now", $utcTimezone);
  397. if (empty($timezone)) {
  398. $userTimezone = new DateTimeZone($prefTimezone);
  399. } else {
  400. $userTimezone = new DateTimeZone($timezone);
  401. }
  402. // default to 1 day
  403. if (empty($startTimestamp) || empty($endTimestamp)) {
  404. $startsDT = clone $utcNow;
  405. $startsDT->sub(new DateInterval("P1D"));
  406. $endsDT = clone $utcNow;
  407. } else {
  408. try {
  409. $startsDT = new DateTime($startTimestamp, $userTimezone);
  410. $startsDT->setTimezone($utcTimezone);
  411. $endsDT = new DateTime($endTimestamp, $userTimezone);
  412. $endsDT->setTimezone($utcTimezone);
  413. if ($startsDT > $endsDT) {
  414. throw new Exception("start greater than end");
  415. }
  416. }
  417. catch (Exception $e) {
  418. Logging::info($e);
  419. Logging::info($e->getMessage());
  420. $startsDT = clone $utcNow;
  421. $startsDT->sub(new DateInterval("P1D"));
  422. $endsDT = clone $utcNow;
  423. }
  424. }
  425. return array($startsDT, $endsDT);
  426. }
  427. }