1

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.

1
  • 3
    Use mktime() or strtotime() Commented Jan 6, 2013 at 10:26

4 Answers 4

1

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";
Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

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 ?
@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.
0

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

Comments

0
$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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.