I am trying to design some functionality in Wordpress where a user can create an "event" with a date they enter, which is something in the format of "MM/DD/YYYY". I want events to be archived if the inputted date is after the current date, so I've been doing something like...
$date = get_post_meta( get_the_ID(), 'Date', true );
$todaysDate = date('n\/d\/Y');
if( $date < $todaysDate) {
// do stuff
}
Obviously, this is not the right way I should be going about this, but I'm not really sure what the best way to handle these inputted dates would be. The way I currently have it set up actually somewhat works, but months of October(10), November(11) and December(12) throw a wrench into the comparison. What would be a better, correct way to go about this?
Use strtotime() to parse about any English textual datetime description into a Unix timestamp. then do the comparison.
if (strtotime($date) < strtotime($todaysDate))
{
// Do more stuff
When comparing dates literally they must be in same format. Here is an enample of how to convert date from meta field to 'Y-m-d'
format:
$date = date( 'Y-m-d', strtotime( get_post_meta( get_the_ID(), 'Date', true ) ) );
$today = date( 'Y-m-d' );
if ( $date < $today ) {
var_dump( $date, $today );
}
This can be done easier if textual dates are converted to Unix timestams with strtotime()
:
if ( strtotime( get_post_meta( get_the_ID(), 'Date', true ) ) < strtotime( date( 'Y-m-d' ) ) ) {
echo 'do stuff';
}