Show content based on date (date before, date after, date between) - php

This is setup to show a button between 2 dates set. And to show a "Sign up starts at xxx" before the set start up date, and "Sign up closed the xxxx" after the set end date...
Somehow nothing shows for the "active periode" / the dates in betweeen...
$DateToday = date('Ymd');
$DateStart = get_field('pamelding_fra');
$DateEnd = get_field('pamelding_slutt');
$DateStartOut = new DateTime($DateStart);
$DateEndOut = new DateTime($DateEnd);
if ($DateStart >= $DateToday){
$ClassStatus = "<div class=\"OpenClassButton\"><span class=\"ClassFullWarning\">Påmeldingen åpner " . $DateStartOut->format('j M Y') . "</span></div>";
$ClassButton = $ClassStatus;
}elseif ($DateEnd <= $DateToday){
$ClassStatus = "<div class=\"OpenClassButton\"><span class=\"ClassFullWarning\">Påmeldingen stengte " . $DateEndOut->format('j M Y') . "</span></div>";
$ClassButton = $ClassStatus;
}elseif ($DateStart <= $DateToday && $DateEnd >= $DateToday){
//Do some stuff - show button, this is the active time.
}
Might not be best-practice and I might make stuff difficult for me, suggestions appriciated.

Don't compare dates using date strings. If they are in different formats (like Ymd, mdY etc) you will get unwanted results. Use unix timestamps instead.
$today = time(); // Get today's timestamp
if ($today < strtotime($DateStart)) {
// Do stuff before
} elseif ($today > strtotime($DateEnd)) {
// Do stuff after
} else {
// Active. No need for any conditions here,
// since we only have three states.
}

Related

Compare dates in different years php [duplicate]

How can I compare two dates in PHP?
The date is stored in the database in the following format
2011-10-2
If I wanted to compare today's date against the date in the database to see which one is greater, how would I do it?
I tried this,
$today = date("Y-m-d");
$expire = $row->expireDate //from db
if($today < $expireDate) { //do something; }
but it doesn't really work that way. What's another way of doing it?
If all your dates are posterior to the 1st of January of 1970, you could use something like:
$today = date("Y-m-d");
$expire = $row->expireDate; //from database
$today_time = strtotime($today);
$expire_time = strtotime($expire);
if ($expire_time < $today_time) { /* do Something */ }
If you are using PHP 5 >= 5.2.0, you could use the DateTime class:
$today_dt = new DateTime($today);
$expire_dt = new DateTime($expire);
if ($expire_dt < $today_dt) { /* Do something */ }
Or something along these lines.
in the database the date looks like this 2011-10-2
Store it in YYYY-MM-DD and then string comparison will work because '1' > '0', etc.
Just to compliment the already given answers, see the following example:
$today = new DateTime('');
$expireDate = new DateTime($row->expireDate); //from database
if($today->format("Y-m-d") < $expireDate->format("Y-m-d")) {
//do something;
}
Update:
Or simple use old-school date() function:
if(date('Y-m-d') < date('Y-m-d', strtotime($expire_date))){
//echo not yet expired!
}
I would'nt do this with PHP.
A database should know, what day is today.( use MySQL->NOW() for example ), so it will be very easy to compare within the Query and return the result, without any problems depending on the used Date-Types
SELECT IF(expireDate < NOW(),TRUE,FALSE) as isExpired FROM tableName
$today = date('Y-m-d');//Y-m-d H:i:s
$expireDate = new DateTime($row->expireDate);// From db
$date1=date_create($today);
$date2=date_create($expireDate->format('Y-m-d'));
$diff=date_diff($date1,$date2);
//echo $timeDiff;
if($diff->days >= 30){
echo "Expired.";
}else{
echo "Not expired.";
}
Here's a way on how to get the difference between two dates in minutes.
// set dates
$date_compare1= date("d-m-Y h:i:s a", strtotime($date1));
// date now
$date_compare2= date("d-m-Y h:i:s a", strtotime($date2));
// calculate the difference
$difference = strtotime($date_compare1) - strtotime($date_compare2);
$difference_in_minutes = $difference / 60;
echo $difference_in_minutes;
You can convert the dates into UNIX timestamps and compare the difference between them in seconds.
$today_date=date("Y-m-d");
$entered_date=$_POST['date'];
$dateTimestamp1 = strtotime($today_date);
$dateTimestamp2 = strtotime($entered_date);
$diff= $dateTimestamp1-$dateTimestamp2;
//echo $diff;
if ($diff<=0)
{
echo "Enter a valid date";
}
I had that problem too and I solve it by:
$today = date("Ymd");
$expire = str_replace('-', '', $row->expireDate); //from db
if(($today - $expire) > $NUMBER_OF_DAYS)
{
//do something;
}
Here's my spin on how to get the difference in days between two dates with PHP.
Note the use of '!' in the format to discard the time part of the dates, thanks to info from DateTime createFromFormat without time.
$today = DateTime::createFromFormat('!Y-m-d', date('Y-m-d'));
$wanted = DateTime::createFromFormat('!d-m-Y', $row["WANTED_DELIVERY_DATE"]);
$diff = $today->diff($wanted);
$days = $diff->days;
if (($diff->invert) != 0) $days = -1 * $days;
$overdue = (($days < 0) ? true : false);
print "<!-- (".(($days > 0) ? '+' : '').($days).") -->\n";
Found the answer on a blog and it's as simple as:
strtotime(date("Y"."-01-01")) -strtotime($newdate))/86400
And you'll get the days between the 2 dates.
This works because of PHP's string comparison logic. Simply you can check...
if ($startdate < $date) {// do something}
if ($startdate > $date) {// do something}
Both dates must be in the same format. Digits need to be zero-padded to the left and ordered from most significant to least significant. Y-m-d and Y-m-d H:i:s satisfy these conditions.
If you want a date ($date) to get expired in some interval for example a token expiration date when performing a password reset, here's how you can do:
$date = $row->expireDate;
$date->add(new DateInterval('PT24H')); // adds 24 hours
$now = new \DateTime();
if($now < $date) { /* expired after 24 hours */ }
But in your case you could do the comparison just as the following:
$today = new DateTime('Y-m-d');
$date = $row->expireDate;
if($today < $date) { /* do something */ }
first of all, try to give the format you want to the current date time of your server:
Obtain current date time
$current_date = getdate();
Separate date and time to manage them as you wish:
$current_date_only = $current_date[year].'-'.$current_date[mon].'-'.$current_date[mday];
$current_time_only = $current_date['hours'].':'.$current_date['minutes'].':'.$current_date['seconds'];
Compare it depending if you are using donly date or datetime in your DB:
$today = $current_date_only.' '.$current_time_only;
or
$today = $current_date_only;
if($today < $expireDate)
hope it helps

PHP if date is older than X days

I have some problems with dates. I need make if like --->
if your activity is less than 1 day do somethink
else if your activity is more than 1 day and less than 3 do moething else
else if your activity is more than 3 do moething else
I need this in PHP. My actual code is:
if (strtotime(strtotime($last_log)) < strtotime('-1 day') ) {
$prom .= "" . json_encode('last_activity') . ": " . json_encode("inactive less than 1 day") . ",";
} else if (strtotime($last_log) > strtotime('-1 day') && strtotime($last_log) < strtotime('-3 day')) {
$prom .= "" . json_encode('last_activity') . ": " . json_encode("inactive more than 1 day and less than 3 days") . ",";
} else if (strtotime($last_log) > strtotime('-3 day')) {
$prom .= "" . json_encode('last_activity') . ": " . json_encode("inactive more than 3") . ",";
}
I think I really don't understand date calculations.
Date_diff is much easier in this case:
$datetime1 = date_create(); // now
$datetime2 = date_create($last_log);
$interval = date_diff($datetime1, $datetime2);
$days = $interval->format('%d'); // the time between your last login and now in days
see: http://php.net/manual/en/function.date-diff.php
Or in your way:
if(strtotime($last_log) < strtotime('-1 day')){
// it's been longer than one day
}
If you want to do it with strtotime, do it like this:
date_default_timezone_set('SOMETHING FOR YOU');
$last_log = '-0.5 day';
$last_log_time = strtotime($last_log);
$minus1day_time = strtotime('-1 day');
$minus3day_time = strtotime('-3 day');
echo $last_log_time . "<br>";
echo $minus1day_time . "<br>";
echo $minus3day_time . "<br>";
if ($last_log_time < $minus3day_time)
{
echo "inactive more than 3";
}
elseif ( ($last_log_time <= $minus1day_time) && ($last_log_time >= $minus3day_time) )
{
echo "inactive more than 1 day and less than 3 days";
}
elseif ($last_log_time > $minus1day_time)
{
echo "inactive less than 1";
}
Couple things I changed from your code:
remove the strtotime(strtotime()). Do not do it twice!
For your second if, I added parentheses to ensure correct evaluation of conditions.
I reversed the order of your if. First check if it is very old (so < -3). Then check if it is between -3 and -1. Then check between -1 and now.
Added <= and >=. The = cases were missing from your code. So if the last_log was == -1, it was not processed ever.
I replace "else if" by "elseif".
I used variables because recalculating strtotime all over is wasteful. And it makes the code less readable IMHO.
Then apply the json_encode comment.
To explain why the logic was reversed:
the last login of a user will always be before now.
lets say that the user's last_login is 5 days ago. strtotime($last_login) will be smaller than strtotime('-1 days'), so the if will be true. But that is not what the OP wants! He wants here the case where the last login is older than 3 days.
Remember that we are comparing numbers in the past, so the smaller, the older.
$dateLog = new DateTime($last_log); // format if needed
$tomorrow = new DateTime("tomorrow");
$yesterday = new DateTime("yesterday");
$threeDaysAgo = new DateTime("-3 days");
if ($dateLog < $yesterday) {
// Do what you want
} else if ($dateLog > $yesterday && $dateLog < $threeDaysAgo) {
// Do another thing
} else if ($dateLog > $threeDaysAgo) {
// ...
}
The doc is here : http://php.net/manual/en/datetime.diff.php

Getting the next date of a day in MySQL database (PHP)

I have a series of weekly events in a database along with the day they happen on (in full form, so: 'Monday', 'Tuesday' etc). I've successfully printed the events in a while loop ordered by today, tomorrow, etc, but I'd like to put the date in brackets next to each one.
I thought it might be a case of (mock code):
$today = date("l");
$todays_date = date("j M");
if (day == $today) {
$date = $todays_date;
}
else if (day == $today + 1) {
$date = $todays_date + 1;
}
else if (day == $today + 2) {
$date = $todays_date + 2;
}
etc...
But I'm not so sure. It'd be ideal if I could just have the date in the database, but this seems to go against the grain of what MySQL is about.
Also, I'd like to ideally format the date as: 11 Jun.
EDIT
Presumably it's also got to fit into my while loop somehow:
if($result && mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$items[] = array($row[0]);
echo "<option>" . $row[0] . "</option>";
}
}
You can use strtotime?
echo "Today: ".date("j M");
echo "Tomorrow: ".date("j M", strotime("+1 day"));
You can use strtotime:
echo strtotime("+1 day");

Show relative time that changes to default date after Midnight

I would like to show "posted Today at" if the posted was posted today, and I know how to do that, but I would like it to show the default date and time format as of 12:01am, obviously because ita no longer posted "today", is there a way I can do this? Thanks for the help.
Thanks, I'll try that, here is what i have.
if($params['time'] > (time() - (60*60*24))){
$old_time = $params['time'];
$hm = date("g:ia", $old_time);
$today = elgg_echo('friendly_time_today', array($hm));
return $today;
return $today;
} else if($params['time'] > (time() - (60*60*48))){
$old_time = $params['time'];
$hm = date("g:ia", $old_time);
$yesturday = elgg_echo('friendly_time_yesturday', array($hm));
return $yesturday;
return $yesturday; }
Do you mean like this:
<?php
$sSaved = "11:08am 01.01.2012"; // comes from date("H:ia d.m.Y");
$aSaved = explode(" ", $sSaved);
if ($aSaved[1] != date("d.m.Y")) {
echo $sSaved;
} else {
echo "today";
}
If I understand your post correctly, this might make sense somehow:
# example function
function stylePostDateExample (DateTime $postDate) {
# get current date
$currDate = date_create(date('Y-m-d H:i:s'));
# grab the interval between the post date and current date
$intervalObj = date_diff($postDate, $currDate);
# simple output start
$stringOut = "Posted ";
# interpret difference
if ($intervalObj->format('%d') < 1 && $intervalObj->format('%y%m') == 0){
# still within the day
$stringOut .= "today at " . $intervalObj->format('%H:%I');
} else {
# the post date day has passed
$stringOut .= "on " . date_format($postDate, 'Y-m-d H:i:s');
}
return $stringOut;
}
# test: any previous day
$postDate = date_create('2012-01-01 00:00:00');
echo stylePostDateExample ($postDate);
# results
# -----------------------------------------
# Posted on <date value here>
# test: today
$postDate = date_create(date('Y-m-d'));
echo stylePostDateExample ($postDate);
# results
# -----------------------------------------
# Posted today at <time value here>
The function requires a datetime value which I suppose you get from the database (for the post's date of creation/posting) and it outputs a string as presented.
If I'm missing the point, please let me know.

Date sorting of PHP Event

I have an events calender that displays events in the order of start date. Everything works great but there is one issue. Events that occur on today's date don't display. I believe that my "if" statement to remove events after they have passed is the issue.
<? while($row = mysql_fetch_assoc($result)) {
$id = $row['id'];
$title = $row['title'];
$text = $row['text'];
$image_url = $row['image_url'];
$start_date = date('F d, Y', strtotime($row['start_date']));
$start_hour = $row['start_hour'];
$start_minute = $row['start_minute'];
$start_am_pm = $row['start_am_pm'];
$end_date = date('F d, Y', strtotime($row['end_date']));
$end_hour = $row['end_hour'];
$end_minute = $row['end_minute'];
$end_am_pm = $row['end_am_pm'];
$tba = $row['tba'];
if(strtotime($row['end_date']) > date('U')) {
?>
First of all, I just want to point out that:
date('U') == time()
So you can use time instead of date.
Now for your problem. If the end_date of your event is set to today, it's probably at the beginning of the day (i.e.: 2010-11-18 00:00:00). That's probably why your conditional does not work, because now is past midnight, the current date/time is greater than the end_date.
Try this:
if (strtotime($row['end_date']) == strtotime('TODAY')) {
// event is today
}
I'm guessing that $row['end_date'] only returns the date not the time. So strtotime($row['end_date']) will = 12:00AM and date('U') will equal return the current time.
So if you ran this at 12:01AM on the date of $row['end_date'], you'd have the comparison of
if("12:00AM today" > "12:01AM today") {
Try
if (strtotime($row['end_date']) >= strtotime(date('Y-m-d'))) {

Categories