Here's what I need to do:
开发者_C百科- I want to insert a date into a datetime MySQL field 30 days from from the current date
- When I pull that specific record, I want to be able to check whether that date has passed yet or not (i.e. expiration date)
INSERT INTO the_table
(fields, the_date_field)
VALUES
(?, DATE_ADD(NOW(), INTERVAL 30 DAY))
SELECT
the_date_field < NOW() AS expired
FROM
the_table
Confirm:
SELECT '2010-01-01' < NOW() AS expired;
+---------+
| expired |
+---------+
| 1 |
+---------+
SELECT '2012-01-01' < NOW() AS expired;
+---------+
| expired |
+---------+
| 0 |
+---------+
For your insert:
$thirty_days_from_today = date('Y-m-d H:i:s', time() + 60*60*24*30);
Checking expiration dates:
if(strtotime($row['expiration_date']) < time()) {
// expired
}
Strtotime is your friend on this one, both for ensuring that the input you're sending through data is "understandable" by PHP and also for doing math such as "+10 days" which would return the date ten days from today. It's really amazing what you can throw at strtotime.
Checking dates is as simple in a MySQL query or PHP comparison with an operator -- Like >, < <>, etc.
Since you're using PHP, you can utilize strtotime()
$date = date( 'Y-m-d', strtotime( '+30 days' ) );
strtotime
can handle other increments (+1 days
, +5 minutes
, etc)
You can also use strtotime
to compare the dates when you read them out of the database. If you're storing in full-day (no timestamp) format, you'll need to divide by a full day's worth of seconds.
$expdate = strtotime( date( 'Y-m-d', $record[ 'expiration_date' ] ) );
$today = strtotime( date( 'Y-m-d' ) );
$isExpired = round( abs( $expiration - $today ) / ( 24 * 60 * 60 ) ) >= 0;
精彩评论