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.
4 Answers
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";
Comments
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:
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
2 Comments
Sideshow
Can't seem to get this working - whenever I add variables it just stalls the script ie: ('H:ia d/m/Y', '$time $date') or ('H:ia d/m/Y', $time $date). What is the correct syntax ?
Ian Atkin
@Sideshow See my edit above. PHP allows for variables to be inserted in double quotes (in most cases), so you can drop your variables into a string as the second parameter (or create a var containing
time and date). Make sure you use double quotes; single quotes will not work.You could use strtotime()
Call it by putting in your variables.
strtotime("9.30 1/2/2012");
Comments
$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
mktime()orstrtotime()