For a project, i need to convert multiple values form an array to a time format in PHP. I've got arrays like this:
starttime = ['year' => 2019, 'month' => 5, 'day' => 10, 'hour' => 20, 'minute' => 15]
Is there a way to convert these values to a time format with which i can also calculate stuff? I already tried using strtotime, but it dind't work.
Thanks for your answers!
-
By time format do you mean unix timestamp?Will B.– Will B.2019-01-31 15:04:43 +00:00Commented Jan 31, 2019 at 15:04
-
Do you mean something like this ? sandbox.onlinephpfunctions.com/code/…executable– executable2019-01-31 15:08:19 +00:00Commented Jan 31, 2019 at 15:08
1 Answer
I suggest using the DateTime object which has the setDate, setTime and getTimestamp methods. Which you can use for defining the date and time from the array keys, and retrieve the unix timestamp as a result.
Example: https://3v4l.org/o3lVr
$starttime = ['year' => 2019, 'month' => 5, 'day' => 10, 'hour' => 20, 'minute' => 15];
$date = new \DateTime();
$date->setDate($starttime['year'], $starttime['month'], $starttime['day']);
$date->setTime($starttime['hour'], $starttime['minute']);
var_dump($timestamp = $date->getTimestamp());
var_dump(date('Y-m-d H:i:s', $timestamp));
Results:
int(1557512100)
string(19) "2019-05-10 20:15:00"
Optionally to prevent issues with missing keys, in PHP >= 7.0 you can use the null coalesce operator ?? to default the values to the current date.
Example: https://3v4l.org/0MOI5
$starttime = ['month' => 5, 'day' => 10, 'minute' => 15];
$date = new \DateTime();
$date->setDate($starttime['year'] ?? $date->format('Y'), $starttime['month'] ?? $date->format('m'), $starttime['day'] ?? $date->format('d'));
$date->setTime($starttime['hour'] ?? $date->format('H'), $starttime['minute'] ?? $date->format('i'));
var_dump($timestamp = $date->getTimestamp());
var_dump(date('Y-m-d H:i:s', $timestamp));
Results:
int(1557497700)
string(19) "2019-05-10 16:15:00"
Alternatively you can also use mktime to produce the same result. Please note, as per the manual, in PHP < 5.1.0 this method may produce unexpected (but not incorrect) results if DST is not specified.
Example: https://3v4l.org/DU0Q1
$starttime = ['year' => 2019, 'month' => 5, 'day' => 10, 'hour' => 20, 'minute' => 15];
$timestamp = mktime(
$starttime['hour'],
$starttime['minute'],
0,
$starttime['month'],
$starttime['day'],
$starttime['year']
);
var_dump($timestamp);
var_dump(date('Y-m-d H:i:s', $timestamp));
Results:
int(1557512100)
string(19) "2019-05-10 20:15:00"