True only on Weekdays and at a specific time - php

I am using PHP 7.4.1 and Laravel Framework 6.20.12 with the carbon library.
I want to return true only once from Monday to Friday if a date crosses the $sendPost variable. My cron-job runs every 5 Minutes.
I tried:
<?php
require 'vendor/autoload.php';
use Carbon\Carbon;
function checkMsgFired() {
$now = Carbon::now();
// $now = Carbon::createFromFormat('d/m/Y H:i:s', "19/1/2021 14:43:00");
$lastSendPost = Carbon::createFromFormat('d/m/Y H:i:s', "18/1/2021 14:43:00"); // the posting has already happended today
$post = array();
$post['Frequency'] = "MoToFr"; // send only from monday to friday at a specific date once
$post['sendPost'] = Carbon::createFromFormat('H:i:s', "14:40:00"); // when the post should be send
if($post['Frequency'] === "MoToFr") {
// if it is a WEEKDAY
if($now->dayOfWeek !== Carbon::SATURDAY or $now->dayOfWeek !== Carbon::SUNDAY) {
// $lastPosting didn't happen today
if(!$lastSendPost->isToday() && $now->gt($post['sendPost'])){
return true;
}
else{
return false;
}
} else {
return false;
}
}
}
var_dump(checkMsgFired());
However, the posting time does not seem to work. How can I check that the event has already fired once at the exact time?
Furthermore, is there an easier version to code this?
I appreciate your replies!

Something like possibly? This’ll give you true when the time is between 14:40 and 14:45, so long as your cron job runs every 5 minutes it should be mostly correct.
<?php
require 'vendor/autoload.php';
use Carbon\Carbon;
function checkMsgFired() {
$now = Carbon::now();
$frequency = "MoToFr";
$sendPost = Carbon::createFromFormat('H:i:s', "14:40:00");
if ($frequency === "MoToFr") {
if ($now->isWeekday()) {
return $now->between($sendPost, $sendPost->addMinutes(5));
}
}
return false;
}
var_dump(checkMsgFired());

Related

Function to check user birth date is 18 years or upper not always work correctly

I am beginner webdeveloper.
I use in my project Laravel 5.8.
I have this this code:
if ($this->calcutateAge($request->input('date')) < 18) {
return Redirect::back()->withErrors(['You are a minor. Registration is allowed for adult users']);
}
function calcutateAge($dob)
{
$dob = date("Y-m-d", strtotime($dob));
$dobObject = new DateTime($dob);
$nowObject = new DateTime();
$diff = $dobObject->diff($nowObject);
return $diff->y;
}
It's work fine. But I have problem with date ex 2045-12-12.
This function is not working. With year: 2015-12-12 - it's okey.
How can I repair it?
I suggest you should use Carbon.
use Carbon\Carbon;
function calcutateAge($dob){
return \Carbon::parse($dob)->age;
}
I would write your function to return true or false depending on if the user is 18 or not.
function is_18($dob)
{
$dobObject = new DateTime(date("Y-m-d", strtotime($dob)));
$nowObject = new DateTime();
return $dobObject < $nowObject ? ($dobObject->diff($nowObject)->y > 18) : false;
}
Then your IF block is simplified to this:
if (!$this->is_18($request->input('date')) {
return Redirect::back()->withErrors(['You are a minor. Registration is allowed for adult users']);
}
I would find out when a person born 18 years ago was born, then compare to that:
function isAdult($dob) {
$adult = new DateTime('18 years ago'); // 'date' => '2002-09-01 12:05:52.000000'
$dob = date("Y-m-d", strtotime($dob));
$dobObject = new DateTime($dob);
return $adult >= $dobObject; // 2002-09-01 is after the passed date of birth
}
you can add 18 year and compare the date like this:
$dobObject = new DateTime($dob.' +18 years');
$nowObject = new DateTime();
if ($dobObject > $nowObject)
print 'great you are granted'
else
print 'sorry you are minor'
If you run var_dump($diff); you will see:
["invert"]=> int(1)
Which means is a negative difference.
So, you can do return $diff->invert? -$diff->y : $diff->y;
Of course this is a solution based on your code. You can always check if the date is someday into the future, and return false or throw some exception in this case.

Validate datetime input for scheduling

I have a scheduling system school project,
I need to create a function that validates the date entered by the user,
check if it is 2 days ahead, not Sunday and it is between working hours.
Im using codeigniter framework.
//my controller looks like this:
public function checkDateTimeInput(){
$dateTimeInput = $this->input->post('dateTimeInput');
if($dateTimeInput /*Greater than 2 days or more*/ && /*not sunday*/ && /*between 8AM-5PM*/){
return true;
}else{
return false;
}
}
//in my view:
<?php echo form_open('schedules/checkDateTimeInput'); ?>
<input type="datetime-local" name="dateTimeInput">
<input type="submit" value="submit">
</form>
For completion's sake, I'm going to consider <input type="datetime-local" name="dateTimeInput"> as the input.
So this basically creates this format:
d/m/Y h:i A
I tried it on my browser (Chrome) and it does that. More info here also:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/datetime-local
So taking that into consideration, you can use createFromFormat to parse the input and use DateTime class.
$input = DateTimeImmutable::createFromFormat('d/m/Y h:i A', $dateTimeInput);
$dt = new DateTime; // now
if (
($input >= $input->setTime(8, 0) && $input <= $input->setTime(17, 0)) && // time is between 8 to 5
$input->format('l') !== 'Sunday' && // is not sunday
$dt->diff($input)->d >= 2 // is greater or more than two days
) {
return true;
}
return false;
Here's a sample output
Sidenote: I should also point out that type="datetime-local" is not supported in Firefox browser and should consider using a real date time plugin instead. If the user happens to use Firefox, you should prepare a fall back.
You can use below function and call it from your controller.
function checkDateConditions( $dateTimeInput ) {
//Make DateTime Object using the input
$inputDate = new DateTime( $dateTimeInput );
//Get the Hour from the Date Input
$inputHour = $inputDate->format('G');
//Check Time is between 8AM and 5PM ( 5PM is = 17)
if( $inputHour < 8 || $inputHour > 17) {
return false;
}
//This Returns 7 for Sunday
$dayOfWeek = $inputDate->format('N');
//If its Sunday we return false
if( $dayOfWeek == 7) {
return false;
}
//Calculate Date Difference
$now = new DateTime( Date('Y-m-d') );
$diff = $inputDate->diff($now);
//If date difference is greater than 2 days return false
if( $diff->days > 2 ) {
return false;
}
//If it reaches here it means all conditions are met so retrun true.
return true;
}

How do I compare current time to a preset time in PHP?

I want PHP to check if it's 8:30 AM and if it is, I want it to change a variable.
I tried,
$eightthirtyam = "08:30:00";
if(time() >= strtotime($eightthirtyam )){
$refresh = true;
}
But the boolean doesn't change. Any idea what I did wrong?
strtotime depends on the time zone.. so you should define timezone too.
You should set your default timezone before comparing.
http://php.net/strtotime
Example:
date_default_timezone_set('America/Los_Angeles');
$eightthirtyam = "08:30:00";
if(time() >= strtotime($eightthirtyam )){
$refresh = true;
}
http://codepad.org/GC0VA7nw
The function time() returns always timestamp that is timezone independent (=UTC), while strtotime() give a local time, So there is a timezone offset.
You need to subtract the timezone offset form the local time, before the compare, and check the live demo for a good understanding.
In php we have new DateTime function. So you can use this to match your date as give below example
$refresh = false;
$eightthirtyam = "08:30:00";
$date = new DateTime();
if($date->format('H:i:s') == $eightthirtyam)
{
$refresh = true;
}
Here is an example
$refresh = "false";
$eightthirtyam = "08:30:00";
$date = new DateTime("2017-06-07 8:30:00"); // suppose your system current time is this.
if($date->format('H:i:s') == $eightthirtyam)
{
$refresh = "true";
}
echo $refresh;
You can check answer by executing on online php editor http://www.writephponline.com/
Try above example, I think this may help you.
$hr= date('H:i');
if(strtotime($hr)==strtotime(08:30) ){
$refresh = true;
}
Please try this way. It will work i your case.
This will help you:
date_default_timezone_set('Asia/Kolkata');
$eightthirtyam = "08:30:00";
$refresh = false;
if(strtotime(date('H:i:s') == strtotime($eightthirtyam )){
$refresh = true;
}
Reference:-/ strtotime
the code is fine untill i know. but still if you want to do some actions, you can do something like this.
$refresh=false;
$eightthirtyam = "08:30:00";
if(time() >= strtotime($eightthirtyam ))
{
$refresh = true;
}
if($refresh)
{
//your statement is true do something here
}
else
{
//false statement
}

PHP - how to validate if current time is matched with given timezone start and end

How can i make current date/time validate with given timezone/start/end?
outside $meeting_for, $meeting_starts till $meeting_ends range, all should return false.
$meeting_for = 'America/Los_Angeles';
$meeting_starts ='2016-10-11 00:00:00';
$meeting_ends = '2016-10-11 06:00:00';
function give_meeting_result_based_on_rightnow() {
// PHP server time
date_default_timezone_set('Europe/Brussels');
$etime1 = date('Y-m-d H:i:s');
$date = new DateTime($etime1, new DateTimeZone('Europe/Brussels'));
// PHP server time converted to meeting time
$date->setTimezone(new DateTimeZone($meeting_for));
$logic_check= $date->format('Y-m-d H:i:s') . "\n";
if($logic_check is between ($meeting_starts till $meeting_ends )) {
return true;
}
else {
return false;
}
}
echo give_meeting_result_based_on_rightnow();
The solution is quite simple, but you made a few mistakes. The variables at the top aren't in global scope. They're not available inside the function. Therefor you either need to put them inside the function, or pass them along as parameters (as I did in the code below). After that it's a very simple check with an if statement:
<?php
// These are NOT global. They're not available within the scope of the function
$meeting_for = 'America/Los_Angeles';
$meeting_starts ='2016-10-11 00:00:00';
$meeting_ends = '2016-10-11 06:00:00';
function give_meeting_result_based_on_rightnow($timeZone, $startTime, $endTime) {
// PHP server time
date_default_timezone_set('Europe/Brussels');
$etime1 = date('Y-m-d H:i:s');
$date = new DateTime($etime1, new DateTimeZone('Europe/Brussels'));
// PHP server time converted to meeting time
$date->setTimezone(new DateTimeZone($timeZone));
$logic_check= $date->format('Y-m-d H:i:s') . "\n";
if ($logic_check >= $startTime && $logic_check <= $endTime)
{
return true;
} else {
return false;
}
}
// Passing along the variables as parameters to the function
echo give_meeting_result_based_on_rightnow($meeting_for, $meeting_starts, $meeting_ends);
?>
Keep in mind that the echo() won't actually give any output. You need to return a string for that instead of a boolean.
EDIT:
$ var_dump_this_code_with_curdate('2016-10-10 07:54:32')
bool(false)

Add current time to database and when reading it later check if that time has passed

So I'd like to add the current time to the database, to a specific user when he does something, and later on read it, and check if that time has passed (by checking current time and substracting that from the one in database; to check if it has passed or not)
So how would I do this? I tried with something like this:
$date = date("YmWjis");
$calculate = $date - $info['lastvisit'];
if($calculate <= -1)
{
echo "you need to wait before visiting again"; // (just an example)
} else {
//do something
}
I also tried both:
!$calculate < 0
$calculate < 0
etc. But I can't get it to work. Can anyone help me? :P
edit for Parag;
$date = date("YmWjis");
$dote = date("YmWjis") + $time; // ($time is set earlier and is 30 seconds)
echo "wait " . $date = $date - $dote . " seconds until next visit";
work?
It says like "wait 20138269786674 seconds until next visit".
You can try something like this:
$dateDiff = new DateTime("2014-04-27 22:00:15");
$date = new DateTime();
$diff = $date->diff($dateDiff);
if($diff->invert == 0)
{
echo "you need to wait before visiting again"; // (just an example)
} else {
//do something
}
$db_time = "2014/04/28 15:15:15";
$cur_time = "2014/04/28 18:15:15";
if(strtotime($cur_time) > strtotime($db_time))
{
// Current time exceeds DB time
$diff = date('Y/m/d H:i:s', strtotime($cur_time)-strtotime($db_time));
echo $diff;
}
else
{
// Current time didn't exceeds DB time
}
UPDATE
$date = strtotime(date("YmWjis"));
$dote = strtotime(date("YmWjis")) + $time; // ($time is set earlier and is 30 seconds)
echo "wait " . $date = $date - $dote . " seconds until next visit";
DEMO
http://3v4l.org/LBIXu
Don't use a database. This does the job without the db overhead. It uses PHP sessions.
<?php
session_start();
if (!isset($_SESSION['lastVisitTime'])) {
$_SESSION['lastVisitTime']=new DateTime();
} else {
$now=new DateTime();
if ($_SESSION['lastVisitTime']->diff($now) > $someMaxValueYouDefine) {
echo "You must wait before visiting again.";
}
}

Categories