I am currently working on an app and have some issues with the date handling. Found a simple solution, and want your opinion. First thing, that I want to achieve:
- I have 2 date format inputs, one is like 2013-09-30 14:20:00 and the other is 30/09/2013 1420
- Time stamp is given with no day light saving time.
So, I have to store my date/time in DB with the same format in order to compare one with each other, and also I need to adjust the time stamp +1 hour if it is in the DST period. For this, I made the following function:
function format_date($date_string, $date_format)
{
$unix = mktime( substr($date_string, strpos($date_format, 'HH'), 2),
(strpos($date_format, 'ii'))? substr($date_string, strpos($date_format, 'ii'), 2) : '00',
(strpos($date_format, 'ss'))? substr($date_string, strpos($date_format, 'ss'), 2) : '00',
substr($date_string, strpos($date_format, 'MM'), 2),
substr($date_string, strpos($date_format, 'DD'), 2),
substr($date_string, strpos($date_format, 'YYYY'), 4)
) ;
$human = date('Y-m-d H:i:s', $unix);
$dst = date('I', $unix);
return (object)array(
'unix' => $unix,
'human' => $human,
'dst' => $dst
);
}
//Usage:
$date1 = format_date('2013-09-30 14:20','YYYY-MM-DD HH:ii');
$date2 = format_date('30/09/2013 1420','DD/MM/YYYY HHii');
echo $date1->human ;
echo '<br />';
echo $date2->human ;
echo '<br />';
// $date1->human is the same with $date1->human, also ->unix
Maybe this will help others, but if you find something not right in this function please let me know before I put it in production.
Update: (thank you Glavić)
function format_date1($date_string, $date_format)
{
$date_build = DateTime::createFromFormat ( $date_format , $date_string );
return (object)array(
'unix' => $date_build->format('U'),
'human' => $date_build->format('Y-m-d H:i:s'),
'dst' => $date_build->format('I')
);
}
$make_date = format_date1('30/09/2013 1420', 'd/m/Y Hi');
print_r($make_date);
//returns stdClass Object ( [unix] => 1380540000 [human] => 2013-09-30 14:20:00 [dst] => 1 )
//Use: $make_date->unix | $make_date->human | $make_date->dst
DateTime::createFromFormat
andDateTime::format
– 1ed Oct 2 '13 at 8:15