time greater than another time - php

I am preparing a small php attendance script which will record the time and date of given user.
I am trying to display a message that if person is LATE after given time php to display a message you are late
$CURRENTTIME = new DateTime($data['current_time']);
$CURRENTTIME = $CURRENTTIME->format('H:i:s');
$OFFICETIME = new DateTime('10:20:00');
$OFFICETIME = $OFFICETIME->format('H:i:s');
var_dump($CURRENTTIME);
var_dump($OFFICETIME);
if ($CURRENTTIM > $OFFICETIME) {
echo 'you are late tody';
} else {
echo 'Thank you for being on time';
}
also i wanted to learn the code if i need a result in between time? let say i need to display result if employee is in between 10:00:00 - 10:30:00

DateTime objects are comparable so no need to compare their formatted strings. Just compare the objects themselves.
$CURRENTTIME = new DateTime($data['current_time']);
$OFFICETIME = new DateTime('10:20:00');
if ($CURRENTTIME > $OFFICETIME) {
echo 'you are late tody';
} else {
echo 'Thank you for being on time';
}
See this answer for how to see if a time is between two times. It's pretty much the same concept.
Sidenote: There was a typo in your code. $CURRENTTIM which should read as $CURRENTTIME.

Related

Laravel Carbon plus or minute one minute for comparing time

I am working on a notification then checks every minute for a scheduled notification. It never calls it because my now variable is in a minute format (2021-01-28 10:27) where as the database send_date is stored (2021-01-28 10:15:11)
$now = date("Y-m-d H:i", strtotime(Carbon::now()));
$notifications = Notification::get();
if($notifications !== null)
{
Log::info('Notifications are not null ' .$now); // shows in log (2021-01-28 10:27)
$notifications->where('send_date', $now)->each(function($message) {
Log::info('looking at send_date'); // never shows in log
}
}
Or is there another way of doing this, that I am not seeing?
$notifications = Notification::get();
if($notifications !== null)
{
Log::info('Notifications are not null ' .$now); // shows in log (2021-01-28 10:27)
$notifications->whereBetween('send_date', [Carbon::now()->subMinute()->format('Y-m-d H:i'), Carbon::now()->addMinute()->format('Y-m-d H:i')])->each(function($message) {
Log::info('looking at send_date'); // never shows in log
}
}
Reference :
whereBetween, Carbon
Then you could use the following way
$notifications->whereBetween('send_date', [Carbon::now()->startOfMinute(), Carbon::now()->endOfMinute()])->each(function($message) {
If you need to format the time yourself then:
$notifications->whereBetween('send_date', [Carbon::now()->startOfMinute()->format('Y-m-d H:I:s'), Carbon::now()->endOfMinute('Y-m-d H:I:s')])->each(function($message) {

Events Organiser Wordpress only show if

I want to show "Stay Tuned..." if there are no Upcoming Events.
Sure there is a simple solution here, I've just never worked with the combination of PHP and shortcodes before.
For reference: http://docs.wp-event-organiser.com/shortcodes/events-list/
Upcoming Events
[eo_events event_start_after=today showpastevents=false] %event_title% on %start{jS M Y}{ g:i:a}% [/eo_events]
PastĀ Events
[eo_events event_end_before=today] %event_title% on %start{jS M Y}{ g:i:a}% [/eo_events]
Be aware that the showpastevents parameter will be deprecated some time soon, so might be good to leave it out.
There are a few ways to achieve this. Here's some raw code that will achieve the desired results (using the shortcode; of course you could do the same thing just using functions):
// GET FUTURE ------------------
if (function_exists("eo_get_events")) {
$events = eo_get_events(array(
'event_start_after'=>'today',
));
if ($events) {
echo do_shortcode("[eo_events event_start_after=\"today\"]%event_title% on %start{jS M Y}{ g:i:a}% [/eo_events]");
} else {
echo "Stay Tuned....";
}
}
// GET PAST ------------------
if (function_exists("eo_get_events")) {
$events = eo_get_events(array(
'event_end_before'=>'today'
));
if ($events) {
echo do_shortcode("[eo_events event_end_before=\"today\"]%event_title% on %start{jS M Y}{ g:i:a}% [/eo_events]");
} else {
echo "No Past Events....";
}
}

PHP - Handling dates before and after christ

Im making Biogram on my site which lists known historical figures.
Right now, Im just getting values from database, and on many IF statements, determine what to display.
/* #var $bio \Models\Library\Biography */
$birth = [];
$death = [];
$date = null;
if($bio->getBirthMonth() != null) {
if ($bio->getBirthDay() != null) {
$birth = [
$bio->getBirthDay(),
$bio->getBirthMonth(),
$bio->getBirthYear(),
];
} else {
$birth = [
$bio->getBirthMonth(),
$bio->getBirthYear(),
];
}
} else {
$birth = [
$bio->getBirthYear(),
];
}
if($bio->getDeathMonth() != null) {
if ($bio->getDeathDay() != null) {
$death = [
$bio->getDeathDay(),
$bio->getDeathMonth(),
$bio->getDeathYear(),
];
} else {
$death = [
$bio->getDeathMonth(),
$bio->getDeathYear(),
];
}
} else {
$death = [
$bio->getDeathYear(),
];
}
if (!array_filter($birth) && array_filter($death)) {
$date = 'zm. ' . implode('.', $death);
}
if (array_filter($birth) && !array_filter($death)) {
$date = 'ur. ' . implode('.', $birth);
}
if (!array_filter($birth) && !array_filter($death)) {
$date = null;
}
if (array_filter($birth) && array_filter($death)) {
$date = implode('.', $birth) . ' - ' . implode('.', $death);
}
But first of all, Im not happy with this kind of code (don't know if I can write it better).
Secondly when im using Carbon (for example), and want to display year from medival ages, it looks like 0552 instead of 552.
The last thing is that there is no "year 0" in history. There were year 1 After Christ and 1 Before Christ. So when I want to have year -200 it gives me -199.
I know this may be handled by adding -1 to date if it's BC, but I think this is not the right way.
Is there any php library for DateTime that handles all the Dates well?
Also can I, and if so; how to rewrite this code above to look better?
Cheers :)
This is a very interesting problem.
Firstly your if statements - I would write a helper function within $bio that contains the logic regarding what to display as your date, making reference to the other properties that exist within $bio. You could call it getPrettyDate() or something like that. That's potentially where your logic for getting the year to display correctly would go too.
After some considerable googling and not much luck, this answer seems to be the most helpful on this subject, certainly some food for thought.
It's also worth noting that using DATE when persisting this information to your database (assuming you're using MySQL, which you may well not be) is probably not the way forward in your case - as noted in that answer, the MySQL definition of DATE is the following
DATE
A date. The supported range is '1000-01-01' to '9999-12-31'.
I have also after writing this just stumbled across this answer which might be the best approach. Good luck!
More reading on ISO-8601 in the context of 'Year 0' here.

How can I grab the current timestamp and add minutes to it in CakePHP?

I am trying to add minutes to a timestamp in CakePHP. I want the timestamp to be grabbed when the form is processed.
Keep in mind, I'm just learning this stuff.
Here is my form code in my index view...
<?php
echo $this->Form->create('Text');
$expirations = array('9999999'=>'Never','10'=>'10 Minutes','60'=>'1 Hour','1440'=>'1 Day','10080'=>'1 Week','40320'=>'1 Month','525600'=>'1 Year');
echo $this->Form->input('expiration', array('options' => $expirations), array('empty'=>false));
echo $this->Form->input('title');
echo $this->Form->input('body', array('rows' => '3'));
echo $this->Form->end('Upload');
?>
I want to take the value from my 'expiration' input and add that amount of minutes to the current time.
The PHP code I currently use for this is:
DATE_ADD(CURRENT_TIMESTAMP, INTERVAL $expiration MINUTE)
where $expiration is the number of minutes to add.
Thank you very much for your help.
where did you get the idea that input has more parameters?
it is supposed to be (as documented):
echo $this->Form->input('expiration', array('options' => $expirations, 'empty'=>false));
PS: a good IDE will tell you that via code completion that there is no such param.
As for your question: You can modify the data before saving in several ways:
a) in the controller level
if ($this->request->is('post') || $this->request->is('put')) {
$this->request['Text']['expiration'] += $yourValue; // we modify it first and then save it
if ($this->Text->save($this->request->data)) {...}
}
b) in the model as callback (recommended)
public function beforeValidate($options = array()) {
if (isset($this->data[$this->alias]['expiration'])) {
$this->data[$this->alias]['expiration'] += $yourValue;
}
return true;
}
Won't
$expiration += ($minutes * 60);
do the trick, or did I miss something?

Calculation error, help me find please?

I am running subscriptions on my website.
I have a 1,3,6 and 12 months of subscription, and I would like the user to be able to change that subscription whenever they feel like.
However, I need to calculate the amount of money the user had to pay had he or she signed up for the shorter term, rather the relatively cheap,longer one.
I made this function optimized_subscription_total($active_sub_time,$arr_sub_values) so that it returns that sum of money exactly.
<?php
function optimized_subscription_total($active_sub_time,$arr_sub_values)
{
// This function takes a row from the DB where prices for each period of time usage is listed. there are prices for 1 month, 3 months,6 and 12 months.
// when the user has subscribed for 12 months, and the user asks for a refund, after they used 9 months and 6 days for example, the system treats the refund as if they subscribed for (in months) COST_6 + COST_3 + (COST_1/30)*6
// the result of the function is then subtracted from the amount they actually paid and is considered the refund.
// $arr_sub_values is the associative row from the DB, containing the prices
// $active_sub_time is measured in months and is a double
$result=0;
while(($active_sub_time-12)>=0)
{
$active_sub_time-=12;
$result+=($arr_subscription_values['COST_12']);
}
while(($active_sub_time-6)>=0)
{
$active_sub_time-=6;
$result+=($arr_subscription_values['COST_6']);
}
while(($active_sub_time-3)>=0)
{
$active_sub_time-=3;
$result+=($arr_subscription_values['COST_3']);
}
while(($active_sub_time-1)>=0)
{
$active_sub_time-=1;
$result+=($arr_subscription_values['COST_1']);
}
if($active_sub_time>0)
$result+=($active_sub_time)*($arr_subscription_values['COST_1']);
return $result;
}
$datetime1 = date_create('2009-12-11');
$datetime2 = date_create('2010-11-09');
$interval = date_diff($datetime1, $datetime2);
$num_of_months = ($interval->format('%y'))*12+($interval->format('%m'))+($interval->format('%a'))/30;
echo "<br />";
$v = array('COST_1'=>'3.99','COST_3'=>'9.99','COST_6'=>'15.99','COST_12'=>'25.99');
echo "OPT value for $num_of_months months=" . optimized_subscription_total($num_of_months, $v);
?>
Strangely I get the bug appearing only after 7 to 10 times after refreshing this code.
So I got:
OPT value for 10 months=M.97
as a result here. I think I need to get a float number, no ?
I was expecting the result of the function that should be "OPT value for 10 months=29.97", as it should take COST_6 + COST_3 + COST_1... but I get that weird M.97, and sometimes things like POKHHHG.97
I would change the logic to the following and see if error is still produced. I think this is a little bit more clear and easy to debug. It is the same as your though just explained differently.
while($active_sub_time>=12)
{
$active_sub_time-=12;
$result+=($arr_subscription_values['COST_12']);
}
while($active_sub_time>=6)
{
$active_sub_time-=6;
$result+=($arr_subscription_values['COST_6']);
}
while($active_sub_time>=3)
{
$active_sub_time-=3;
$result+=($arr_subscription_values['COST_3']);
}
while($active_sub_time>=1)
{
$active_sub_time-=1;
$result+=($arr_subscription_values['COST_1']);
}
What I would also do is added debug cod at the top inside function.
echo "<br>$active_sub_time" // debug code include at the top
This will give you an idea, if any garbage being is being sent to the function itself.
Also I would add this test function in all while blocks if the above does not resolve the issue.
if (!is_numeric($result))
{
echo"<br> Bug occurred";break; // print other values if necessary
}

Categories