Question

I have a user input where the user inputs time and date as '9.30am' and '01/02/2012'. I am trying to convert this to a unix timestamp to aid ordering when dragging the data back out of the database but strptime() is confusing me as I am unsure as to whether this is actually returning a unix timestamp that I need.

Was it helpful?

Solution 2

Using PHP's built-in DateTime class...

$objDate = DateTime::createFromFormat('H:ia d/m/Y', '9:30am 1/2/2012');
$timestamp = $objDate->getTimestamp();

...returns a Unix timestamp.

Documentation:

  1. PHP DateTime Class

    a. DateTime::createFromFormat

    b. DateTime::getTimestamp

To add your variables, use it like so...

$objDate = DateTime::createFromFormat('H:ia d/m/Y', "$time $date");
$timestamp = $objDate->getTimestamp();

Or...

$time_date = sprintf("%s %s", $time, $date); // concatenates into a single var
$objDate = DateTime::createFromFormat('H:ia d/m/Y', $time_date);
$timestamp = $objDate->getTimestamp();

Note: Make sure that your variables conform with the following...

$time = hh:mm (and "am" or "pm" is appended)

$date = dd/mm/yyyy

OTHER TIPS

You can use: strtotime

PHP.net Example:

echo strtotime("now"), "\n";
echo strtotime("10 September 2000"), "\n";
echo strtotime("+1 day"), "\n";
echo strtotime("+1 week"), "\n";
echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
echo strtotime("next Thursday"), "\n";
echo strtotime("last Monday"), "\n";

You could use strtotime()

Call it by putting in your variables.

strtotime("9.30 1/2/2012");

http://php.net/manual/en/function.strtotime.php

$date = DateTime::createFromFormat('H:ia d/m/Y' '9:30am 1/2/2012');
$timestamp = $date->getTimestamp();

Is what you are looking for. http://www.php.net/datetime

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top