资讯专栏INFORMATION COLUMN

PHP实现的一个时间帮助类

ky0ncheng / 2429人阅读

摘要:背景工作的过程中经常会遇到各种时间类的操作,因此封装了一个帮助工具类,提高代码的复用率主要功能根据相差的天数获取连续的时间段根据相差的天数获取所有连续的时间段转化查询条件根据两个日期获取连续的时间段根据开始和结束时间获取所

背景

工作的过程中经常会遇到各种时间类的操作,因此封装了一个帮助工具类,提高代码的复用率

主要功能 根据相差的天数获取连续的时间段

</>复制代码

  1. /**
  2. * 根据相差的天数获取所有连续的时间段
  3. * @param $diffDay
  4. * @param string $dateFormat
  5. * @return array
  6. */
  7. public static function getContinuesDayDiffDay($diffDay, $dateFormat = "Y-m-d") {
  8. $today = date("Y-m-d");
  9. $timeLabel = [];
  10. for ($i=1;$i<=$diffDay;$i++){
  11. $diff = $diffDay - $i;
  12. $mday = date($dateFormat,strtotime("$today -$diff day"));
  13. array_push($timeLabel,$mday);
  14. }
  15. //转化查询条件
  16. $year = date("Y");
  17. $startDay = str_replace(".","-",$timeLabel[0]);
  18. $endDay = str_replace(".","-",$timeLabel[$diffDay-1]);
  19. $startTime = strtotime($startDay." 00:00:00");
  20. $endTime = strtotime($endDay." 23:59:59");
  21. return [
  22. "start_time" => $startTime,
  23. "end_time" => $endTime,
  24. "time_label" => $timeLabel,
  25. ];
  26. }
根据两个日期获取连续的时间段

</>复制代码

  1. /**
  2. * 根据开始和结束时间获取所有连续的时间段
  3. * @param string $startDay 开始日期 格式:Y-m-d
  4. * @param string $endDay 开始日期 格式:Y-m-d
  5. * @param string $dateFormat
  6. * @return array
  7. */
  8. public static function getContinuesDayByRange($startDay, $endDay, $dateFormat = "Y-m-d") {
  9. $timeLabel = [];
  10. if(strtotime($startDay) > strtotime($endDay)){
  11. $tmp = $startDay;
  12. $endDay = $tmp;
  13. $startDay = $endDay;
  14. }
  15. if($startDay == $endDay){
  16. array_push($timeLabel,$startDay);
  17. $startTime = strtotime($startDay." 00:00:00");
  18. $endTime = strtotime($endDay." 23:59:59");
  19. $timeLabel = [
  20. "start_time" => $startTime,
  21. "end_time" => $endTime,
  22. "time_label" => $timeLabel,
  23. ];
  24. return $timeLabel;
  25. }
  26. $targetDay = $startDay;
  27. while ($targetDay != $endDay){
  28. array_push($timeLabel,$targetDay);
  29. $targetDay = date($dateFormat,strtotime("$targetDay +1 day"));
  30. }
  31. array_push($timeLabel,$endDay);
  32. //增加
  33. $startTime = strtotime($startDay." 00:00:00");
  34. $endTime = strtotime($endDay." 23:59:59");
  35. $timeLabel = [
  36. "start_time" => $startTime,
  37. "end_time" => $endTime,
  38. "time_label" => $timeLabel,
  39. ];
  40. return $timeLabel;
  41. }
根据日期获取当月的开始时间和结束时间

</>复制代码

  1. /**
  2. * 根据日期获取本月的开始时间和结束时间
  3. * @param $date Y-m 2017-10
  4. * @return array
  5. */
  6. public static function getMonthDaysByDate($date) {
  7. $data = [];
  8. $timestamp = strtotime( $date );
  9. $data["start_time"] = date( "Y-m-01 00:00:00", $timestamp );
  10. $mdays = date( "t", $timestamp );
  11. $data["end_time"] = date( "Y-m-" . $mdays . " 23:59:59", $timestamp );
  12. return $data;
  13. }
时间友好格式化风格

</>复制代码

  1. /**
  2. * 时间友好型提示风格化(即微博中的XXX小时前、昨天等等)
  3. * 即微博中的 XXX 小时前、昨天等等, 时间超过 $time_limit 后返回按 out_format 的设定风格化时间戳
  4. * @param int
  5. * @param int
  6. * @param string
  7. * @param array
  8. * @param int
  9. * @return string
  10. */
  11. public static function getFriendlyTime($timestamp, $timeLimit = 604800, $out_format = "Y/m/d", $formats = null, $now = null){
  12. /*if (get_setting("time_style") == "N")
  13. {
  14. return date($out_format, $timestamp);
  15. }*/
  16. if (!$timestamp)
  17. {
  18. return false;
  19. }
  20. if ($formats == null)
  21. {
  22. $formats = [
  23. "YEAR" =>"%s 年前",
  24. "MONTH" => "%s 月前",
  25. "DAY" => "%s 天前",
  26. "HOUR" => "%s 小时前",
  27. "MINUTE" => "%s 分钟前",
  28. "SECOND" => "%s 秒前"
  29. ];
  30. }
  31. $now = $now == null ? time() : $now;
  32. $seconds = $now - $timestamp;
  33. if ($seconds == 0)
  34. {
  35. $seconds = 1;
  36. }
  37. if (!$timeLimit OR $seconds > $timeLimit)
  38. {
  39. return date($out_format, $timestamp);
  40. }
  41. $minutes = floor($seconds / 60);
  42. $hours = floor($minutes / 60);
  43. $days = floor($hours / 24);
  44. $months = floor($days / 30);
  45. $years = floor($months / 12);
  46. if ($years > 0)
  47. {
  48. $diffFormat = "YEAR";
  49. }
  50. else
  51. {
  52. if ($months > 0)
  53. {
  54. $diffFormat = "MONTH";
  55. }
  56. else
  57. {
  58. if ($days > 0)
  59. {
  60. $diffFormat = "DAY";
  61. }
  62. else
  63. {
  64. if ($hours > 0)
  65. {
  66. $diffFormat = "HOUR";
  67. }
  68. else
  69. {
  70. $diffFormat = ($minutes > 0) ? "MINUTE" : "SECOND";
  71. }
  72. }
  73. }
  74. }
  75. $dateDiff = null;
  76. switch ($diffFormat)
  77. {
  78. case "YEAR" :
  79. $dateDiff = sprintf($formats[$diffFormat], $years);
  80. break;
  81. case "MONTH" :
  82. $dateDiff = sprintf($formats[$diffFormat], $months);
  83. break;
  84. case "DAY" :
  85. $dateDiff = sprintf($formats[$diffFormat], $days);
  86. break;
  87. case "HOUR" :
  88. $dateDiff = sprintf($formats[$diffFormat], $hours);
  89. break;
  90. case "MINUTE" :
  91. $dateDiff = sprintf($formats[$diffFormat], $minutes);
  92. break;
  93. case "SECOND" :
  94. $dateDiff = sprintf($formats[$diffFormat], $seconds);
  95. break;
  96. }
  97. return $dateDiff;
  98. }
根据日期获取是星期几

</>复制代码

  1. /**
  2. * 获取星期几
  3. * @param $date
  4. * @return
  5. */
  6. public static function getWeekDay($date) {
  7. //强制转换日期格式
  8. $dateStr=date("Y-m-d",strtotime($date));
  9. //封装成数组
  10. $arr=explode("-", $dateStr);
  11. //参数赋值
  12. //年
  13. $year=$arr[0];
  14. //月,输出2位整型,不够2位右对齐
  15. $month=sprintf("%02d",$arr[1]);
  16. //日,输出2位整型,不够2位右对齐
  17. $day=sprintf("%02d",$arr[2]);
  18. //时分秒默认赋值为0;
  19. $hour = $minute = $second = 0;
  20. //转换成时间戳
  21. $strap = mktime($hour,$minute,$second,$month,$day,$year);
  22. //获取数字型星期几
  23. $numberWk=date("w",$strap);
  24. //自定义星期数组
  25. $weekArr=array(7,1,2,3,4,5,6);
  26. //获取数字对应的星期
  27. return $weekArr[$numberWk];
  28. }
获取指定日期前后相同时间天数的时间范围

</>复制代码

  1. /**
  2. * 获取指定日期前后相同时间天数的范围时间
  3. * @param int $dayDiff
  4. * @param string $day
  5. * @param string $dateFormat
  6. * @return array
  7. */
  8. public static function getPointDaySameRangeContinuesTime($dayDiff = 0,$day = "", $dateFormat = "Y-m-d") {
  9. $day = $day?$day:date($dateFormat);
  10. $startTime = date($dateFormat,strtotime("$day -$dayDiff day"));
  11. $endTime = date($dateFormat,strtotime("$day +$dayDiff day"));
  12. $result = self::getContinuesDayByRange($startTime,$endTime,$dateFormat = "Y-m-d");
  13. return $result;
  14. }
获取两个日期之间相差的天数

</>复制代码

  1. /**
  2. * 获取两个日期之间相差的天数
  3. * @param string $day1 第一个日期,格式为Y-m-d
  4. * @param string $day2 第二个日期,格式为Y-m-d
  5. * @return integer
  6. */
  7. public static function getDiffBetweenTwoDays($day1, $day2) {
  8. $second1 = strtotime($day1);
  9. $second2 = strtotime($day2);
  10. if ($second1 < $second2) {
  11. $tmp = $second2;
  12. $second2 = $second1;
  13. $second1 = $tmp;
  14. }
  15. return ($second1 - $second2) / 86400;
  16. }
根据指定日期和天数,获取结束的日期

</>复制代码

  1. /**
  2. * 根据日期和相差的天数获取结束的天数
  3. * @param $day
  4. * @param $diffDay
  5. * @param bool $isBefore
  6. * @return false|string
  7. */
  8. public static function getEndDayByDayAndDiff($day, $diffDay, $isBefore = false) {
  9. $operator = $isBefore ? "-" : "+";
  10. $endDay = date("Y-m-d",strtotime("$day $operator $diffDay day"));
  11. return $endDay;
  12. }
判断两个日期是否为同一天

</>复制代码

  1. /**
  2. * 判断两个时间是否同一天
  3. * @param string $date1 Y-m-d
  4. * @param string $date2 Y-m-d
  5. * @return bool
  6. */
  7. public static function isSameDay($date1, $date2) {
  8. $day1 = self::dateTime(strtotime($date1)) ;
  9. $day2 = self::dateTime(strtotime($date2));
  10. return $day1 == $day2;
  11. }
转换秒钟为分钟

</>复制代码

  1. /**
  2. * 转换秒钟为分钟
  3. * @param $seconds
  4. * @return string
  5. */
  6. public static function convertSecondToTime($seconds) {
  7. $reminded = strval($seconds % 60);
  8. $minute = strval(($seconds - $reminded) / 60);
  9. if(strlen($minute)<2){
  10. $minute = "0".$minute;
  11. }
  12. if(strlen($reminded)<2){
  13. $reminded = "0".$reminded;
  14. }
  15. $time = $minute.":".$reminded;
  16. return $time;
  17. }
获取毫秒数

</>复制代码

  1. /**
  2. * 获取时间的毫秒数
  3. * @return float
  4. */
  5. public static function millisecond() {
  6. list($msec, $sec) = explode(" ", microtime());
  7. return (float)sprintf("%.0f", (floatval($msec) + floatval($sec)) * 1000);
  8. }
附录:完整的时间帮助类代码

</>复制代码

  1. $startTime,
  2. "end_time" => $endTime,
  3. "time_label" => $timeLabel,
  4. ];
  5. }
  6. /**
  7. * 根据开始和结束时间获取所有连续的时间段
  8. * @param string $startDay 开始日期 格式:Y-m-d
  9. * @param string $endDay 开始日期 格式:Y-m-d
  10. * @param string $dateFormat
  11. * @return array
  12. */
  13. public static function getContinuesDayByRange($startDay, $endDay, $dateFormat = "Y-m-d") {
  14. $timeLabel = [];
  15. if(strtotime($startDay) > strtotime($endDay)){
  16. $tmp = $startDay;
  17. $endDay = $tmp;
  18. $startDay = $endDay;
  19. }
  20. if($startDay == $endDay){
  21. array_push($timeLabel,$startDay);
  22. $startTime = strtotime($startDay." 00:00:00");
  23. $endTime = strtotime($endDay." 23:59:59");
  24. $timeLabel = [
  25. "start_time" => $startTime,
  26. "end_time" => $endTime,
  27. "time_label" => $timeLabel,
  28. ];
  29. return $timeLabel;
  30. }
  31. $targetDay = $startDay;
  32. while ($targetDay != $endDay){
  33. array_push($timeLabel,$targetDay);
  34. $targetDay = date($dateFormat,strtotime("$targetDay +1 day"));
  35. }
  36. array_push($timeLabel,$endDay);
  37. //增加
  38. $startTime = strtotime($startDay." 00:00:00");
  39. $endTime = strtotime($endDay." 23:59:59");
  40. $timeLabel = [
  41. "start_time" => $startTime,
  42. "end_time" => $endTime,
  43. "time_label" => $timeLabel,
  44. ];
  45. return $timeLabel;
  46. }
  47. /**
  48. * 根据日期获取本月的开始时间和结束时间
  49. * @param $date Y-m 2017-10
  50. * @return array
  51. */
  52. public static function getMonthDaysByDate($date) {
  53. $data = [];
  54. $timestamp = strtotime( $date );
  55. $data["start_time"] = date( "Y-m-01 00:00:00", $timestamp );
  56. $mdays = date( "t", $timestamp );
  57. $data["end_time"] = date( "Y-m-" . $mdays . " 23:59:59", $timestamp );
  58. return $data;
  59. }
  60. /**
  61. * 获取两个月份之间连续的月份
  62. * @param $start
  63. * @param $end
  64. * @return array
  65. */
  66. public static function prDates($start, $end) { // 两个日期之间的所有日期
  67. $time_start = strtotime($start); // 自动为00:00:00 时分秒 两个时间之间的年和月份
  68. $time_end = strtotime($end);
  69. $monarr[] = $start; // 当前月;
  70. while( ($time_start = strtotime("+1 month", $time_start)) <= $time_end){
  71. array_push($monarr,date("Y-m", $time_start));// 取得递增月
  72. }
  73. return $monarr;
  74. }
  75. /**
  76. * 时间友好型提示风格化(即微博中的XXX小时前、昨天等等)
  77. * 即微博中的 XXX 小时前、昨天等等, 时间超过 $time_limit 后返回按 out_format 的设定风格化时间戳
  78. * @param int
  79. * @param int
  80. * @param string
  81. * @param array
  82. * @param int
  83. * @return string
  84. */
  85. public static function getFriendlyTime($timestamp, $timeLimit = 604800, $out_format = "Y/m/d", $formats = null, $now = null){
  86. /*if (get_setting("time_style") == "N")
  87. {
  88. return date($out_format, $timestamp);
  89. }*/
  90. if (!$timestamp)
  91. {
  92. return false;
  93. }
  94. if ($formats == null)
  95. {
  96. $formats = [
  97. "YEAR" =>"%s 年前",
  98. "MONTH" => "%s 月前",
  99. "DAY" => "%s 天前",
  100. "HOUR" => "%s 小时前",
  101. "MINUTE" => "%s 分钟前",
  102. "SECOND" => "%s 秒前"
  103. ];
  104. }
  105. $now = $now == null ? time() : $now;
  106. $seconds = $now - $timestamp;
  107. if ($seconds == 0)
  108. {
  109. $seconds = 1;
  110. }
  111. if (!$timeLimit OR $seconds > $timeLimit)
  112. {
  113. return date($out_format, $timestamp);
  114. }
  115. $minutes = floor($seconds / 60);
  116. $hours = floor($minutes / 60);
  117. $days = floor($hours / 24);
  118. $months = floor($days / 30);
  119. $years = floor($months / 12);
  120. if ($years > 0)
  121. {
  122. $diffFormat = "YEAR";
  123. }
  124. else
  125. {
  126. if ($months > 0)
  127. {
  128. $diffFormat = "MONTH";
  129. }
  130. else
  131. {
  132. if ($days > 0)
  133. {
  134. $diffFormat = "DAY";
  135. }
  136. else
  137. {
  138. if ($hours > 0)
  139. {
  140. $diffFormat = "HOUR";
  141. }
  142. else
  143. {
  144. $diffFormat = ($minutes > 0) ? "MINUTE" : "SECOND";
  145. }
  146. }
  147. }
  148. }
  149. $dateDiff = null;
  150. switch ($diffFormat)
  151. {
  152. case "YEAR" :
  153. $dateDiff = sprintf($formats[$diffFormat], $years);
  154. break;
  155. case "MONTH" :
  156. $dateDiff = sprintf($formats[$diffFormat], $months);
  157. break;
  158. case "DAY" :
  159. $dateDiff = sprintf($formats[$diffFormat], $days);
  160. break;
  161. case "HOUR" :
  162. $dateDiff = sprintf($formats[$diffFormat], $hours);
  163. break;
  164. case "MINUTE" :
  165. $dateDiff = sprintf($formats[$diffFormat], $minutes);
  166. break;
  167. case "SECOND" :
  168. $dateDiff = sprintf($formats[$diffFormat], $seconds);
  169. break;
  170. }
  171. return $dateDiff;
  172. }
  173. /**
  174. * 获取星期几
  175. * @param $date
  176. * @return
  177. */
  178. public static function getWeekDay($date) {
  179. //强制转换日期格式
  180. $dateStr=date("Y-m-d",strtotime($date));
  181. //封装成数组
  182. $arr=explode("-", $dateStr);
  183. //参数赋值
  184. //年
  185. $year=$arr[0];
  186. //月,输出2位整型,不够2位右对齐
  187. $month=sprintf("%02d",$arr[1]);
  188. //日,输出2位整型,不够2位右对齐
  189. $day=sprintf("%02d",$arr[2]);
  190. //时分秒默认赋值为0;
  191. $hour = $minute = $second = 0;
  192. //转换成时间戳
  193. $strap = mktime($hour,$minute,$second,$month,$day,$year);
  194. //获取数字型星期几
  195. $numberWk=date("w",$strap);
  196. //自定义星期数组
  197. $weekArr=array(7,1,2,3,4,5,6);
  198. //获取数字对应的星期
  199. return $weekArr[$numberWk];
  200. }
  201. /**
  202. * 获取指定日期前后相同时间天数的范围时间
  203. * @param int $dayDiff
  204. * @param string $day
  205. * @param string $dateFormat
  206. * @return array
  207. */
  208. public static function getPointDaySameRangeContinuesTime($dayDiff = 0,$day = "", $dateFormat = "Y-m-d") {
  209. $day = $day?$day:date($dateFormat);
  210. $startTime = date($dateFormat,strtotime("$day -$dayDiff day"));
  211. $endTime = date($dateFormat,strtotime("$day +$dayDiff day"));
  212. $result = self::getContinuesDayByRange($startTime,$endTime,$dateFormat = "Y-m-d");
  213. return $result;
  214. }
  215. /**
  216. * 获取两个日期之间相差的天数
  217. * @param string $day1 第一个日期,格式为Y-m-d
  218. * @param string $day2 第二个日期,格式为Y-m-d
  219. * @return integer
  220. */
  221. public static function getDiffBetweenTwoDays($day1, $day2) {
  222. $second1 = strtotime($day1);
  223. $second2 = strtotime($day2);
  224. if ($second1 < $second2) {
  225. $tmp = $second2;
  226. $second2 = $second1;
  227. $second1 = $tmp;
  228. }
  229. return ($second1 - $second2) / 86400;
  230. }
  231. /**
  232. * 根据日期和相差的天数获取结束的天数
  233. * @param $day
  234. * @param $diffDay
  235. * @param bool $isBefore
  236. * @return false|string
  237. */
  238. public static function getEndDayByDayAndDiff($day, $diffDay, $isBefore = false) {
  239. $operator = $isBefore ? "-" : "+";
  240. $endDay = date("Y-m-d",strtotime("$day $operator $diffDay day"));
  241. return $endDay;
  242. }
  243. /**
  244. * 根据时间戳返回日期型时间戳
  245. * @param $time
  246. * @return int
  247. */
  248. public static function dateTime($time) {
  249. return strtotime(date("Y-m-d", $time));
  250. }
  251. /**
  252. * @param $num
  253. * @return string
  254. */
  255. public static function getFriendlyNumber($num) {
  256. if ($num >= 10000) {
  257. $num = round($num / 10000 ,1) ."万";
  258. } else {
  259. $num = $num;
  260. }
  261. return $num;
  262. }
  263. /**
  264. * 判断两个时间是否同一天
  265. * @param string $date1 Y-m-d
  266. * @param string $date2 Y-m-d
  267. * @return bool
  268. */
  269. public static function isSameDay($date1, $date2) {
  270. $day1 = self::dateTime(strtotime($date1)) ;
  271. $day2 = self::dateTime(strtotime($date2));
  272. return $day1 == $day2;
  273. }
  274. /**
  275. * 转换秒钟为分钟
  276. * @param $seconds
  277. * @return string
  278. */
  279. public static function convertSecondToTime($seconds) {
  280. $reminded = strval($seconds % 60);
  281. $minute = strval(($seconds - $reminded) / 60);
  282. if(strlen($minute)<2){
  283. $minute = "0".$minute;
  284. }
  285. if(strlen($reminded)<2){
  286. $reminded = "0".$reminded;
  287. }
  288. $time = $minute.":".$reminded;
  289. return $time;
  290. }
  291. /**
  292. * 获取时间的毫秒数
  293. * @return float
  294. */
  295. public static function millisecond() {
  296. list($msec, $sec) = explode(" ", microtime());
  297. return (float)sprintf("%.0f", (floatval($msec) + floatval($sec)) * 1000);
  298. }
  299. }

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/29854.html

相关文章

  • PHP生成器

    摘要:它最简单的调用形式看起来像一个申明,不同之处在于普通会返回值并终止函数的执行,而会返回一个值给循环调用此生成器的代码并且只是暂停执行生成器函数。 0x01 写在前面 本文主要介绍: Generator的简单用法。 Generator的底层实现。 本文比较长,可能会耗费你比较多的时间。如果你比较了解Generator的用法,仅想了解底层实现,可以直接跳到底层实现部分。 本文分析的PH...

    LMou 评论0 收藏0
  • PHP应用性能优化指南

    摘要:怎样才算是高性能的应用性能和速度不是一对同义词。红线表示针对速度进行了优化的脚本,蓝线是可扩展性优先的脚本。将任何这些功能置于循环中可能会导致性能问题。完整的代码检测评估虽然可能很耗时,但它可以为你提供有关应用程序性能的深入信息。 showImg(https://segmentfault.com/img/bVNxDn?w=900&h=500);程序员都喜欢最新的PHP 7,因为它使PH...

    EddieChan 评论0 收藏0
  • 成为一个PHP专家:缺失环节

    摘要:为了成为一个专家,他必须先成为中级者。它非常适合于急于求成或者没有太多技术的人,但掌握绝对无法使你成为一个专业的开发者它使用意大利面条式的编码,教你的是不合适的设计原则。 这一篇文章是Becoming a PHP Professional系列 4 篇博文中的第 1 篇。 当浏览各类与PHP相关的博客时,比如Quora上的问题,谷歌群组,简讯和杂志,我经常注意到技能的等级分化。问题都类...

    cooxer 评论0 收藏0
  • PHP实现微信小程序支付帮助

    摘要:背景事先准备工作申请一个小程序,并开通微信支付,详细见微信小程序支付业务说明仔细查阅微信支付官方文档,详细见微信支付开发者文档仔细阅读微信支付统一下单接口仔细阅读支付结果通知接口整理并在商户平台设置好相应的回掉地址,比如服务端编写两个接口微 背景 事先准备工作 申请一个小程序,并开通微信支付,详细见:微信小程序支付业务说明 仔细查阅微信支付官方文档,详细见: 微信支付开发者文档 ...

    mcterry 评论0 收藏0
  • 一个 16年毕业生所经历 PHP 面试

    摘要:正确做法是给加索引,还有联合索引,并不能避免全表扫描。 前言:有收获的话请加颗小星星,没有收获的话可以 反对 没有帮助 举报三连 有心的同学应该会看到我这个noteBook下面的其它知识,希望对你们有些许帮助。 本文地址 时间点:2017-11 一个16年毕业生所经历的php面试 一、什么是面试 二、面试准备 1. 问:什么时候开始准备? 2. 问:怎么准备? 三、面试...

    dabai 评论0 收藏0

发表评论

0条评论

ky0ncheng

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<