php刚写的两个函数,验证日期格式和比较日期大小
时间:2006-11-01 来源:jingzhi
//大家可以扩展后支持多种分隔符.现在只支持2006-10-10格式
//测试通过
/**
* 验证日期格式是否正确
*
* @param unknown_type $string
* @return unknown
*/
function is_date_format($string)
{
if ( preg_match("/^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}$/",$string) )
{
$first_sep = strpos($string,"-");
$year = substr($string,0,$first_sep);
$part_month_day = substr($string,$first_sep+1);
$last_sep = strpos($part_month_day,"-");
$month = substr( $part_month_day,0,$last_sep );
$day = substr($part_month_day,$last_sep+1);
if ( checkdate($month, $day, $year) ) {
return 1;
}else{
return 0;
}
}else {
return 0;
}
}
/**
* 比较两个日期的相差天数,第一个减第二个,返回相差天数的绝对值
*
* @param unknown_type $date1
* @param unknown_type $date2
* @return int
*/
function compare2date($date1,$date2="")
{
$first_sep = strpos($date1,"-");
$year1 = substr($date1,0,$first_sep);
$part_month_day = substr($date1,$first_sep+1);
$last_sep = strpos($part_month_day,"-");
$month1 = substr( $part_month_day,0,$last_sep );
$day1 = substr($part_month_day,$last_sep+1);
if ( $date2 == "" ) {
$year2 = date("Y");
$month2 = date("m");
$day2 = date("d");
}else{
$first_sep = strpos($date2,"-");
$year2 = substr($date2,0,$first_sep);
$part_month_day = substr($date2,$first_sep+1);
$last_sep = strpos($part_month_day,"-");
$month2 = substr( $part_month_day,0,$last_sep );
$day2 = substr($part_month_day,$last_sep+1);
}
$result = ( mktime( 0, 0, 0, $month1, $day1, $year1 ) - mktime( 0, 0, 0, $month2, $day2, $year2 ) ) / ( 3600 * 24 );
return abs($result);
}
相关阅读 更多 +