Skip to content

Instantly share code, notes, and snippets.

@jdc-cunningham
Last active January 24, 2023 08:31
Show Gist options
  • Save jdc-cunningham/fc31600555788120a852a52ce307996c to your computer and use it in GitHub Desktop.
Save jdc-cunningham/fc31600555788120a852a52ce307996c to your computer and use it in GitHub Desktop.
PHP date time to date, time split function with period
<?php
// made this way so it only has to be called once
// did a dumb thing using a date/time storage with separate date time fields in MySQL with hourly period in the time part
// harder to sort natively with MySQL
function split_date_time($cur_date_time) {
// split date_time components
$date_time_split = explode(' ', $cur_date_time);
// return array
$date_time_arr = [];
$date_time_arr['date'] = $date_time_split[0];
// deal with period
$cur_hour = explode(':', $date_time_split[1]);
if (intval($cur_hour[0]) > 12) {
// pm case
$date_time_arr['time'] = $cur_hour[0]%12 . ':' . $cur_hour[1] . ' PM';
}
else {
$date_time_arr['time'] = $cur_hour[0] . ':' . $cur_hour[1] . ' AM';
}
return $date_time_arr;
}
// example use
echo split_date_time(2017-08-15 13:10:00)['date']; // outputs date component
echo split_date_time(2017-08-15 13:10:00)['time']; // outputs time component
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment