Friday, August 31, 2007

date class update

I hadn't used the class before i posted it, stupid me, therefore i wasn't aware of the problem inserting the custom dateformat in a sql statement.

Mysql formats the dates as following yyyy-mm-dd hh:mm:ss so i had to convert the custom format into the database format. As you can see the added function dbformat is pretty simple leaving room for self formatted date strings.

In the interface functions i call the dbformat function and that gets the class up and running.




class Datemodel extends Model
{
function Datemodel()
{
parent::Model();
}

/**
*
* interface functions
*
*/

function get($format = 'YmdHis', $date = null)
{
$date = (!isset($date))?$this->timestamp('db'):$this->dbformat($date);
return $this->format($date,$this->preformat($format));
}

function getstr($str,$format = 'YmdHis', $date = null)
{
$date = (!isset($date))?$this->timestamp('db'):$this->dbformat($date);
$sign = substr($str,0,1);
$period = trim(substr($str,1));
return $this->get($format,$this->interval($date,$sign,$period));
}

/**
*
* helper functions
*
*/

function timestamp($type = '')
{
switch($type)
{
case 'db': $query = $this->db->query('select NOW() as ts'); break;
default: $query = $this->db->query('select NOW()+0 as ts'); break;
}
$row = $query->row();
return $row->ts;
}

function format($date,$format)
{
$query = $this->db->query('select date_format("'.$date.'","'.$format.'") as val');
$row = $query->row();
return $row->val;
}

function interval($date,$sign,$period)
{
switch($sign)
{
case '+': $query = $this->db->query('select date_add("'.$date.'", interval '.$period.') as val'); break;
case '-': $query = $this->db->query('select date_sub("'.$date.'", interval '.$period.') as val'); break;
}
$row = $query->row();
return $row->val;
}

function dbformat($date)
{
if(strlen($date) == 14)
{
$year = substr($date,0,4);
$month = substr($date,4,2);
$day = substr($date,6,2);
$hour = substr($date,8,2);
$min = substr($date,10,2);
$sec = substr($date,12,2);
$date = $year.'-'.$month.'-'.$day.' '.$hour.':'.$min.':'.$sec;
}
return $date;
}

function preformat($str)
{
$array = array('%','a','b','c','d','e','h','i','j','k','l','m','p','r','s','u','v','w','x','y','D','H','I','M','S','U','V','W','X','Y');
foreach($array as $char)
{
$str = str_replace($char,'%'.$char,$str);
}
return $str;
}
}
?>


No comments: