简体   繁体   中英

Use am/pm to create php timestamp

I have a couple textboxes that allows a person to enter a time and date. The time is entered with a textbox for hours, a textbox for minutes, a drop down for am/pm and some drop downs for months/hours/years

So, I'd like to combine all of these to create a timestamp out of it and save it to the database.

But i've confused myself in how to do all that to create a proper timestamp, especially with the AM/PM part.

It sounds like you'd just use mktime() . Get the correct hour number by adding 12 for pm, then pass the arguments into the function.

if($is_pm) $hour += 12;
$time = mktime($hour, $minute, $second, $month, $day, $year);

If you're looking for a MySQL timestamp instead of a UNIX timestamp, you have two options:

  1. Build the timestamp in MySQL's format using date() : date('Ymd H:i:s', $time);
  2. Let MySQL do it for you: UPDATE table SET date = FROM_UNIXTIME($time) WHERE foo='bar'

Or you could just store the integer timestamp in the database as an integer.

strtotime will do this:

$timestamp = strtotime("$year-$month-$day $hours:$minutes $am_pm");

Just make sure to zero-pad $month, $day, $hours, and $minutes.

Assuming that you've already checked for valid input, you can use the mktime() function. If PM is selected, just add 12 to the hours. That will give you back a Unix Timestamp. You can pass that result to date() to format the date however you would like.

You can use the following to convert it to a unix timestamp:

strtotime("2009/01/02 12:13:14 PM");
strtotime("2009/01/02 12:13:14 AM");

PHP Manual reference: http://php.net/manual/en/function.strtotime.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM