Nadeem
Nadeem

Reputation: 261

How to validate start and end datetime of a content in php

I am working on a news portal in which a news (content) will expire after a specific time.The problem is i have to show only one news at one time, i am not sure how to validate it and check that if there is already a news exist of the same duration in database?

Note user can add future (upcoming) news too. Example is below

$newsStartDate = '2017-10-10 14:52:10'; 
$newsEndDate = '2017-10-11 14:53:10';

I have 2 datetime type column in database (start,expire) now i have to that weather there is already any news exist in the duration of selected $newsStartDate,$newsEndDate or not.

Upvotes: 3

Views: 320

Answers (1)

vstelmakh
vstelmakh

Reputation: 772

It's better to make this comparison in database with BETWEEN in your SELECT from database. Example:

SELECT * FROM News WHERE datetime BETWEEN 2017-10-10 14:52:10 AND 2017-10-11 14:53:10;

Or in your case:

SELECT * FROM News WHERE start < NOW() AND expire > NOW();

But if you want to compare dates in php you could use comparison operators to deal with dates:

if ($newsDate > $newsStartDate && $newsDate < $newsEndDate) { }

See more here:

PHP check if date between two dates

Upvotes: 1

Related Questions