If Statement with date - php

I am doing an assignment for school, and I get bonus marks if I add a discount on a certain day. I have an actively updating time, using the date function(is it a function?) but I don't know how I would go about making an if statement for this.
Here is my code:
<?php
$t = time();
echo "Date of Purchase: " . (date("Y-m-d", $t));
if(date == "20140224") {
echo $b;
echo "It works!";
}
?>
Obviously I only provided relevant code. Any help is appreciated!

Use DateTime() as DateTime objects are comparable:
$today = new DateTime();
$discountDate = new DateTime('2014-02-24');
if ($today == $discountDate) {
// today is discount day!
}
Tip: No need to use time() to pass a second parameter to date(). date() always assumes "now" when no second parameter is passed

This is untested, but the idea is that you have a function with parameters.
function getPrice($price, $search_date, $happyDays=5) {
if(date('w', strtotime($search_date)) == $happyDays) {
return $price * 0.8; // 20% discount
} else {
return $price; // full price
}
}
Call it like so:
echo "Sum: " . getPrice(100, $_SESSION['purchase_date']);
Ps. I use a session date value, since I think the customer should get the discount if he/she places the order just before midnight :-) (as long as the session is still alive).

Related

How would I compare specific time to the current time in PHP?

I am new to PHP and would like to compare a specific time with the current time. I have tried different tricks but nothing works for me.
Eg.
$my_time = '2:00';
$active='';
//echo "The time is " . date("h:ia");die;
if (date('h:i') > date('h:i', strtotime($myTime))) {
$active='Dinner';
$dinner=1;
}
else
{
$active='Lunch';
$lunch=1;
}
You have variable definition
$my_time = '2:00'
but you're using
strtotime($myTime))
This might help you
$my_time ="14:08:10";
if (time() >= strtotime($my_time)) {
echo "Dinner";
}else echo "Lunch";
This will compare given time with current time
try this one .
$my_time ="14:08:10";
if (time() >= strtotime($my_time))
{
echo "Dinner";
}
else
{
echo "Lunch";
}
if this doesnt work try to add date in to time.
because adding date will make time to be more specific.

Conditional DateDiff

I had visited some of the post retrieving the date difference between 2 dates in SO but it doesn't gave me the answer I was seeking. Same for reading the documentation, I had problem understanding how it works.
I have tried coding it but it doesn't behave like what I was expecting. Here is my code:
<?php
$currentDate = new DateTime();
$createDateJoin = date_create($getDate['date_joined']);
$dateJoin = date_format($createDateJoin, "Y-m-d");
$yearDifference = $currentDate->diff($createDateJoin);
if ($yearDifference->d < 31 && $yearDifference->m = 0 && $yearDifference->y == 0) {
echo $yearDifference->d . " days";
} else if ($yearDifference->m > 3) {
echo $yearDifference->m . " month";
} else if ($yearDifference->y > 1) {
echo $yearDifference->y . " years";
} else {
echo "Not yet assigned";
}
?>
As you can see from my code above, I am trying to do a print when after calculating the difference between the 2 dates, it meets the condition of $yearDifference->.The behavior from the program that I have experienced does not print out the things I want accordingly (E.g Staff working more than 1 year will print out how many years they have work, months for those who just came in and new staff less than a month will print out days).
I would like to know how does ->d/m/y works and how can I actually make use of the d,m and y to draw out the specific date correctly. And I also noticed that when I treat $yearDifference as a String or int, it comes out different result for the conditions. So what should I treat the type to be to manipulate it more easily? Greatly appreciate the help.
You can use this code to get the date different method diff() object returns more values to check you can print_r your object that will print all data member that are returned via diff() method
<?php
echo get_date_diff(strtotime('1990-10-12'),strtotime('2015-10-14'));
function get_date_diff($date,$dateEnd) {
$dStart = new DateTime(date("Y-m-d", $date));
$dEnd = new DateTime(date("Y-m-d", $dateEnd));
$dDiff = $dStart->diff($dEnd);
return($dDiff->y.' years <br>'.$dDiff->m.' months <br>'.$dDiff->d. ' days');
}
?>

Echoing something out on a specific date every year

So I'm trying to make a message appear on one specific date of the year.
My code now:
<?php
$year = date("Y");
if(checkdate(5, 22, $year) === TRUE) {
echo '<b>something</b>';
}else {
echo '';
}
?>
But the message appears howsoever, no matter the date.
Hope you can help me,
Thanks in advance!
If you don't have to use checkdate, this is an alternative.
<?php
if (date('Y-m-d') == date('Y').'-05-22') {
echo '<b>something</b>';
} else {
echo '';
}
?>
According to the documentation checkdate only validates dates, it doesn't compare them against the current date.
Returns TRUE if the date given is valid; otherwise returns FALSE.
Use something similar to the code you already have to check the date
if( date("n j") == "5 22")
{
echo '<b>something</b>';
}

Creating discount system for specific period

I'm using CodeIgniter, I want to offer discount for limited period of time. I don't know how to code it, would sessions be okay? But what if I want it only for first 15 mins, how can I manage that?
You can try something like this:
You might have to change your logic slightly to make this work.
<?php
function discount_period($field,$time)
{
$t = time();
$t0 = $_SESSION[$field];
$diff = $t - $t0;
if ($time > 1500 || !isset($t0))
{
return true;
}
else
{
$_SESSION[$field] = time();
}
}
/* Inside your header */
if(discount_period("user_time",1500))
{
session_unset();
session_destroy();
location("some-other-page.php");
exit;
}
?>
I don't know how you gonna do it but you can use this snippet of code as a reference.
<?php
$userLoggedInDate = new DateTime('now'); //The time user logged in. You can store it in the session variable the first time the user had logged in.
$promoDate = 'April 26, 2014';
$date = new DateTime($promoDate); //promo start date
$date2 = new DateTime($promoDate.'+15 min'); //add 15 mins to the date
var_dump($userLoggedInDate>$date2); //is logged in date greater than the promo end time?
var_dump($userLoggedInDate<$date2); //is logged in date less than the promo end time?

How do I calculate time period blocks in PHP, and determine current one?

We have a service that has people paid out in a rolling two week block timeframe:
03-31-13 to 04-13-13
04-14-13 to 04-27-13
04-28-13 to 05-11-13
etc
We want to pay people out on dates that would reflect the pay period that ended a week prior:
04-20-13 would be the payout date for the time period 03-31-13 to 04-13-13
05-04-13 would be the payout date for the time period 04-14-13 to 04-27-13
And so forth
What would be the best way to calculate these time periods and somewhat 'rolling' intervals in PHP? I am no stranger to the DateTime class, but I am not quite sure how to approach this.
Basically, the idea is that when a user lands on their billing page, we can tell them what time period they are in, and when they can expect to be paid for the previously ended time period.
update
After giving it further thought, it almost seems as though I would need to give it some kind of reference point, to know where to start from. Any ideas?
Thank you.
UPDATE #2 - My Solution
class PayoutDate {
const PERIOD_LENGTH = 14;
public static $now;
public static $refStart;
public static $currentMonth;
public static $currentYear;
public static $currPeriodStart;
public static $currPeriodEnd;
public static $prevPeriodStart;
public static $prevPeriodEnd;
public function initialize(Controller $controller) {
self::$now = new DateTime();
self::$currentMonth = self::$now->format('m');
self::$currentYear = self::$now->format('Y');
self::$refStart = new DateTime("10/20/2013");
}
public function getPreviousPeriodStart() {
$daysIntoCurrentPeriod = ((int)self::$now->diff(self::$refStart)->format('%a') % self::PERIOD_LENGTH);
self::$prevPeriodStart = new DateTime('2 weeks ago');
self::$prevPeriodStart->sub(new DateInterval('P'.$daysIntoCurrentPeriod.'D'));
return self::$prevPeriodStart;
}
public function getPreviousPeriodEnd() {
$daysLeftCurrentPeriod = self::PERIOD_LENGTH - ((int)self::$now->diff(self::$refStart)->format('%a') % self::PERIOD_LENGTH) - 1;
self::$prevPeriodStart = new DateTime('2 weeks ago');
self::$prevPeriodStart->add(new DateInterval('P'.$daysLeftCurrentPeriod.'D'));
return (self::$prevPeriodStart);
}
public function getCurrentPeriodStart() {
$daysIntoCurrentPeriod = (int)self::$now->diff(self::$refStart)->format('%a') % self::PERIOD_LENGTH;
self::$currPeriodStart = clone self::$now;
self::$currPeriodStart->sub(new DateInterval('P'.$daysIntoCurrentPeriod.'D'));
return (self::$currPeriodStart);
}
public function getCurrentPeriodEnd() {
$daysLeftCurrentPeriod = self::PERIOD_LENGTH - ((int)self::$now->diff(self::$refStart)->format('%a') % self::PERIOD_LENGTH) - 1;
self::$currPeriodEnd = clone self::$now;
self::$currPeriodEnd->add(new DateInterval('P'.$daysLeftCurrentPeriod.'D'));
return (self::$currPeriodEnd);
}
public function getPreviousPeriodPayout() {
$prevEnd = new DateTime(self::getPreviousPeriodEnd());
return ($prevEnd->modify('next friday'));
}
public function getCurrentPeriodPayout() {
$currentEnd = new DateTime(self::getCurrentPeriodEnd());
return ($currentEnd->modify('next friday'));
}
}
I welcome feedback or improvements to this solution :)
Well, I think you're right about needing some sort of reference point. I would pick an arbitrary start time of one your pay periods. It doesn't matter if it's in the past or future. You're also going to need a variable representing the length of a pay period. Then it's just a matter of doing some math.
$refStart = new DateTime('2013-03-31');
$periodLength = 14;
$now = new DateTime();
// do some modular arithmetic :)
$daysIntoCurrentPeriod = (int)$now->diff($refStart)->format('%a') % $periodLength;
$currentPeriodStart = clone $now;
$currentPeriodStart->sub(new DateInterval('P'.$daysIntoCurrentPeriod.'D'));
So after you run that code, $currentPeriodStart will store the date of the start of the current pay period. (It won't be accurate down to the second, but the date will be correct.) Then you can just subtract 14 days from it to get the start of the previous period, and add/subtract whatever you need to get the pay day.
This solution has the added benefit of working with daylight savings (which can be annoying) since I'm pretty sure DateTime accounts for that.
This works for me using some rules:
Determinate next Saturday (pay day) of given date and add 1 week
You can do some adjustments for your requirements, hope it helps:
<?php
/*
* Using:
* http://stackoverflow.com/a/1485512/496176
* http://www.php.net/manual/es/datetime.add.php
*/
date_default_timezone_set('Europe/London');
$interval = new DateInterval('P1W');
$payPeriod1 = new DateTime("2013-04-13");
$payPeriod1
->setISODate($payPeriod1->format("Y"), $payPeriod1->format("W"), 6)
->add($interval);
print "Pay day: " . $payPeriod1->format('Y-m-d') . "\n"; // Pay day: 2013-04-20
$payPeriod2 = new DateTime("2013-04-27");
$payPeriod2
->setISODate($payPeriod2->format("Y"), $payPeriod2->format("W"), 6)
->add($interval);
print "Pay day: " . $payPeriod2->format('Y-m-d') . "\n"; // Pay day: 2013-05-04
?>

Categories