+ -
当前位置:首页 → 问答吧 → 第二题

第二题

时间:2008-10-16

来源:互联网

[code]
/*
*对日期进行加减操作,当输入日期有误时,提示出错
*/
class php_date
{

var $year;
var $month;
var $day;
function php_date($date="")
{
$this->set_date($date);
}

/**
* 设置日期
*/
function set_date($date="")
{
if(preg_match('/^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})/i',$date,$t))
{
$this->set_year($t[1]);
$this->set_month($t[2]);
$this->set_day($t[3]);
}
else
{
$this->year = date('Y');
$this->month = date('m');
$this->day = date('d');
}
}

/**
* 设置年,1970到2100之间
*/
function set_year($year)
{
$year = intval($year);
$this->year = ($year<=2100 && $year>=1970) ? $year : "日期出错";
}

/**
* 设置月,1到12之间
*/
function set_month($month)
{
$month = intval($month);
$this->month = ($month<13 && $month>0) ? $month : "日期出错";
}

/**
* 设置天,1到31之间
*/
function set_day($day)
{
$day = intval($day);
$this->day = ($day<=$this->get_lastday() && $day>0) ? $day : "日期出错";
}
/**
* 得到当前月份的最后一天
*/
function get_lastday()
{
if($this->month==2)
{
$lastday = $this->is_leapyear() ? 29 : 28;
}
elseif($this->month==4 || $this->month==6 || $this->month==9 || $this->month==11)
{
$lastday = 30;
}
else
{
$lastday = 31;
}
return $lastday;
}

/**
* 判断当前年份是否为闰年
*/
function is_leapyear($year=0)
{
$year = $year ? $year : $this->year;
return ($year%400 == 0 || ($year%4 == 0 && $year%100 != 0)) ? 1 : 0 ;
}

/**
* 返回当前日期
*/
function get_date()
{
return $this->year.'-'.$this->month.'-'.$this->day;
}

/**
* 返回当前Unix 时间戳
*/
function get_time()
{
return strtotime($this->get_date());
}

function get_add($add_day)
{
return date('Y-m-d',strtotime ("+{$add_day} day",strtotime($this->get_date())));
}
function get_sub($sub_day)
{
return date('Y-m-d',strtotime ("-{$sub_day} day",strtotime($this->get_date())));
}
} [/code]
执行:
$cms_date = new php_date("2008-02-29");       //设置日期
echo "当前日期:".$cms_date->get_date()."<br>";
echo $cms_date->get_add(100)."<br>";              //增加100天   
echo $cms_date->get_sub(100)."<br>";              //减去100天

作者: zhaoangel   发布时间: 2008-10-16