php 对比日期与判断日期是否合法类
对比日期与判断日期是否合法类 提供了对比两个日期之间的天数,判断日期是否合法,对比日期大小的方法。经测试 isDate 方法执行1W次,耗时 2.5s 同等条件下 checkdate函数 耗时 3.3 s。
提供了对比两个日期之间的天数,判断日期是否合法,对比日期大小的方法。经测试 isDate 方法执行1W次,耗时 2.5s 同等条件下 checkdate 函数 耗时 3.3 s。 isDate 方法比 checkdate 还多校验了 H:i:s 数值。
[PHP]代码
<?php
/**
* Util_Date
*
*/
class Util_Date {
/**
* 比较 startDate 到 endDate 有多少天
*
* @param $date1
* @param $date2
*
* @returns
*/
public static function calcDiffDays($startDate, $endDate, $round = false) {
// 0000-00-00,2012-12-33 之类的特殊和非法日期
if (!self::isDate($startDate) || !self::isDate($endDate)) {
throw new Exception('参数不是合法的日期');
}
$startTime = strtotime($startDate);
$endTime = strtotime($endDate);
$seconds = abs($endTime - $startTime);
if ($round) {
// 四舍五入方式
return round($seconds/86400);
}
// 只取整数部分,舍去小数方式
return floor($seconds/86400);
}
/**
* 对比日期的方法,验证日期有效性
* $bigDate > $smallDate 返回 > 0
* $bigDate < $smallDate 返回 < 0
* $bigDate = $smallDate 返回 = 0
*
* @param $bigDate
* @param $smallDate
*
* @returns
*/
public static function dateCmp($bigDate, $smallDate) {
if (!self::isDate($bigDate) || !self::isDate($smallDate)) {
throw new Exception('参数不是合法的日期');
}
return strcmp($bigDate, $smallDate);
}
public static function isDate($dateTime, $checkTime = false) {
$strArray = explode(' ', $dateTime);
$date = $strArray[0];
$time = $strArray[1];
// 不是 dateTime 格式
if (!$date || !$time) {
return false;
}
$dateArray = explode('-', $date);
$year = $dateArray[0];
$month = $dateArray[1];
$day = $dateArray[2];
// 年在 1-9999 年
if (!self::_checkLimit($year, 1, 9999)) {
return false;
}
if (!self::_checkLimit($month, 1, 12)) {
return false;
}
if (!self::_checkLimit($day, 1, 31)) {
return false;
}
if ($checkTime) {
$timeArray = explode(':', $time);
$hour = $timeArray[0];
$minute = $timeArray[1];
$second = $timeArray[2];
if (!self::_checkLimit($hour, 0, 24)) {
return false;
}
if (!self::_checkLimit($minute, 0, 60)) {
return false;
}
if (!self::_checkLimit($second, 0, 60)) {
return false;
}
}
return true;
}
/**
* 检查字符串是否在 start to 的区间内
*
* @param $str
* @param $start
* @param $to
*
* @returns
*/
private static function _checkLimit($str, $start, $to) {
if ($str < $start || $str > $to) {
return false;
}
return true;
}
}
精彩图集
精彩文章






