Last active
December 17, 2015 01:49
-
-
Save ishtaka/5531006 to your computer and use it in GitHub Desktop.
英語日付フォーマットから([January or Jan] 1st 2013 00:00 AM)からYYYY-MM-DD方式へフォーマット
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* format-to-YYY-MM-DD | |
* | |
* @param string $date format:[January or Jan] 1st 2013 00:00 AM | |
* @return string $formatedDate format:YYYY-MM-DD hh:mm | |
*/ | |
function date_format_std($date) | |
{ | |
$pattern = '/^([a-z]+)\s([a-z0-9]+)\s([0-9]{4})\s([0-2][0-9]:[0-6][0-9])\s(am|pm)/i'; | |
preg_match($pattern, $date, $matches); | |
if (count($matches) < 1) { | |
return false; | |
} | |
list(, $month, $day, $year, $time, $meridiem) = $matches; | |
$monthArray = array( | |
'jan'=>'01', | |
'feb'=>'02', | |
'mar'=>'03', | |
'apr'=>'04', | |
'may'=>'05', | |
'jun'=>'06', | |
'jul'=>'07', | |
'aug'=>'08', | |
'sep'=>'09', | |
'oct'=>'10', | |
'nov'=>'11', | |
'dec'=>'12', | |
'january'=>'01', | |
'february'=>'02', | |
'march'=>'03', | |
'april'=>'04', | |
'may'=>'05', | |
'june'=>'06', | |
'july'=>'07', | |
'august'=>'08', | |
'september'=>'09', | |
'october'=>'10', | |
'november'=>'11', | |
'december'=>'12' | |
); | |
$month = strtolower($month); | |
if (!array_key_exists($month, $monthArray)) { | |
return false; | |
} | |
$day = (int)substr($day, 0, -2); | |
if (strtolower($meridiem) === 'pm') { | |
$explodeTime = explode(":", $time); | |
$hour = $explodeTime[0] + 12; | |
if ($hour == 24) { | |
$hour = "00"; | |
} | |
$time = $hour . ":" . $explodeTime[1]; | |
} | |
$formatedDate = $year . '-' . $monthArray[$month] . '-' . sprintf('%02d', $day) . ' ' . $time; | |
return $formatedDate; | |
} | |
// こっちのほうが良かった | |
function date_format_std($date) | |
{ | |
$pattern = '/^([a-z]+)\s([a-z0-9]+)\s([0-9]{4})\s([0-2][0-9]:[0-6][0-9])\s(am|pm)/i'; | |
if(0 === preg_match($pattern, $date)) { | |
return false; | |
} | |
$meridiem = substr($date, -2); | |
$datetime = substr($date, 0, -3); | |
$dateTimeObj = new DateTime($datetime); | |
$unixtime = $dateTimeObj->format('U'); | |
if ('pm' == strtolower($meridiem)) { | |
$unixtime = $unixtime + 43200; | |
} | |
return date('Y-m-d H:i', $unixtime); | |
} | |
// strtotimeで出来た... | |
$datetime = 'January 3rd 2013 10:23 PM'; | |
$date = date('Y-m-d H:i', strtotime($datetime)); | |
//string(16) "2013-01-03 22:23" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment