i'm trying to do a contract management app using php and mysql and i'm having some questions regarding the dates.
I need to know the time that there is between today and specific dates in the contract, or if there is less than a month it should display days left..
the problem is that the comparison to know if the end of contract is in the past or in the future, does'n seems to work!
link to check the code: link to project
$hoje = date_create();
$fim = '2022-11-11';
$fim_data = date_create($fim);
$diff = date_diff( $hoje, $fim_data );
$meses = (($diff->format('%y')*12)+$diff->format('%m'));
$dias = $diff->days;
var_dump($fim < $hoje);
if($fim < $hoje) {
$result = "Contract has ended";
} elseif($meses >=1 ) {
$result = $meses . " months";
echo '<br>';
} else {
$result = $dias . " days";
};
echo '<br>';
echo $result;
You are comparing string with date object
Replace
if($fim < $hoje) {
With
if($fim_data < $hoje) {
Corrected code with solution by Felippe Duarte
$hoje = date_create();
$fim = '2018-11-11';
$fim_data = date_create($fim);
$diff = date_diff( $hoje, $fim_data );
$meses = (($diff->format('%y')*12)+$diff->format('%m'));
$dias = $diff->days;
var_dump($fim_data < $hoje);
if($fim_data < $hoje){$result = "não aplicavel";}
elseif($meses >=1 ){
$result = $meses . " meses";
echo '<br>';}
else{
$result = $dias . " dias";};
echo '<br>';
echo $result;
Related
I have a php script here to create login at our datacenter for myself, but this script is doing the login for next week if i run it after 12:00 on monday, and a lot of times I'm not there the whole week, so I want to improve this script by asking for user input and pass the dates that I will be there so the script only picks up on those dates. I know i have to do this with stdin and I do have a part that works, but i have no idea on how to integrate this into the current script and how to make sure i can give multiple dates
My stdin part that does ask my for a date, but no idea on how to combine it:
<?php
function promptDateFromUser(string $prompt, string $dateFormat): DateTimeInterface
{
echo "{$prompt} [$dateFormat]: ";
$stdin = fopen('php://stdin', 'r');
$line = trim(fgets(STDIN));
fclose($stdin);
$dateTime = DateTimeImmutable::createFromFormat('Y-m-d', $line);
if (! $dateTime instanceof DateTimeInterface) {
throw new UnexpectedValueException('Invalid datetime format');
}
}
$dateTime = promptDateFromUser("Please insert date:", 'Y-m-d');
?>
My login script as of now:
<?php
require 'shared.php';
restore_exception_handler();
restore_error_handler();
$md = new RevisionModificationData;
$md->comment = 'Set by the dcgaccess script';
$date = new DateTime();
$hour = (int)$date->format('H');
$dow = (int)$date->format('w');
if (($dow === 1 && $hour > 12) || ($dow > 1 && $dow < 6)) {
$add = 'P' . (8 - $dow) . 'D';
$date->add(new DateInterval($add));
}
if (($dow === 1 && $hour <= 12) || $dow === 0 || $dow === 6) {
if ($dow === 6) {
$date->add(new DateInterval('P2D'));
} elseif ($dow === 0 ) {
$date->add(new DateInterval('P1D'));
}
}
$tomorrow = $date->format('Y-m-d');
$duration = 720;
$customerId = 30;
$purpose = 'DCG visit';
$phoneNumber = '';
$name = 'SOME NAME, REMOVED FOR PUBLICATION';
$colo = Colo::getByName($name);
Ensure::notNull($colo, "Colo for RackSpace is null when it should not be!");
$spaces = $colo->getRackSpaces();
foreach ($spaces as $space) {
$rackSpace = $space;
}
Ensure::notNull($rackSpace, "RackSpace is null when it should not be!");
if ($colo->getCustomerId() != $customerId) {
throw new UserException(ErrorCodes::PERMISSION_DENIED);
}
for ($x = 0; $x < 5; $x++) {
$start = $tomorrow." 8:00:00";
$end = Util::stringToMysqlDateTime($start . ' + ' . $duration . ' minutes');
$shouldSms = strlen((string)$phoneNumber) > 0;
$req = BioAccessRequest::create($rackSpace, $purpose, $start, $end, $shouldSms, $md);
$users = BioAccessUser::getAll();
foreach ($users as $user) {
if ($user->name === 'USER NAME') {
$req->addBioAccessUser($user, $md);
}
}
$req->request();
echo "Access requested for: ", $tomorrow, PHP_EOL;
$date->add(new DateInterval('P1D'));
$tomorrow = $date->format('Y-m-d');
}
?>
I'm a big php noob, so some explanation is greatly appreciated!
after some help from a friend, i managed to solve this:
#!/usr/bin/env php
<?php
include('shared.php');
restore_exception_handler();
restore_error_handler();
// Constants
$timeout = 45;
$md = new \RevisionModificationData;
$md->comment = 'Set by the dcgaccess script';
$duration = "720";
$customerId = "30";
$purpose = "DCG visit";
$phoneNumber = "";
$name="SOME NAME, REMOVED FOR PUBLICATION";
// Functions
function requestInput($msg) {
global $timeout;
echo "$msg\n\nThe timeout for this selection is $timeout seconds.\n\n> ";
$fd = fopen('php://stdin', 'r');
$read = array($fd);
$write = $except = array(); // we don't care about this
if(stream_select($read, $write, $except, $timeout)) {
$choice = trim(fgets($fd));
}
echo "\nYou typed: $choice\n\n";
return $choice;
}
// Start of program
$date = new DateTime();
$weekchoice = (int)requestInput("Which week would you like to request access for?\n1) Current week\n2) Next week\n3) Specific week number");
if ($weekchoice == 3) {
$weeknumber = (int)requestInput("Please enter a numeric week number");
} else {
$weeknumber = (int)$date->format("W");
if ($weekchoice == 2) {
$weeknumber += 1;
}
}
// We override $date with the start of the chosen week
$date->setISODate($date->format("Y"), $weeknumber);
echo "Thanks, you chose week $weeknumber which starts with " . $date->format("l d F, Y") . " \n\n";
$dayschoice = requestInput("Please enter the days you want access, as a space separated list:\n1) Monday\n2) Tuesday\n3) Wednesday\n4) Thursday\n5) Friday\n\nExample: 1 3 5");
$daylist = explode(' ', $dayschoice);
$processedDays = [];
foreach ($daylist as $eachday) {
$iday = (int)$eachday;
if ($iday == 0 || $iday % 7 == 0) { // No Sundays, also (int)"" -> 0, which is terrible
continue;
}
$add_days = $iday - 1; // Sums 0 if Monday, 1 if Tuesday and so on...
$newdate = new DateTime($date->format("Y-m-d"));
$newdate->modify("+$add_days days");
$processedDays[] = $newdate;
$formatted = $newdate->format("l d F Y");
echo "Processing day $iday, which is $formatted\n";
}
$hour = $date->format('H');
$tomorrow = $date->format('Y-m-d');
$confirm = requestInput("\nRequest access for these days? Yes/No");
if ($confirm != "Yes") {
echo 'Good bye!';
exit(0);
}
foreach ($processedDays as $reqDay) {
echo "Submitting " . $reqDay->format("l d F Y") . "\n";
$colo = Colo::getByName($name);
Ensure::notNull($colo, "Colo for RackSpace is null when it should not be!");
$spaces = $colo->getRackSpaces();
foreach ($spaces as $space) {
$rackSpace = $space;
}
Ensure::notNull($rackSpace, "RackSpace is null when it should not be!");
if ($colo->getCustomerId() != $customerId) {
throw new UserException(ErrorCodes::PERMISSION_DENIED);
}
}
foreach ($processedDays as $reqDay) {
$start = $reqDay->format('Y-m-d')." 8:00:00";
$end = Util::stringToMysqlDateTime($start . ' + ' . $duration . ' minutes');
$shouldSms = strlen((string)$phoneNumber) > 0;
$req = BioAccessRequest::create($rackSpace, $purpose, $start, $end, $shouldSms, $md);
$users = BioAccessUser::getAll();
foreach ($users as $user) {
if ($user->name === 'USER NAME') {
$req->addBioAccessUser($user, $md);
}
}
$req->request();
echo "Access requested: ", $reqDay->format('l d F Y'), PHP_EOL;
$tomorrow = $date->format('Y-m-d');
}
?>
We are creating a system where employees need to update their daily status report. The fundamental purpose of the system is to note the missing dates on which they did not update the status report.
I have found a way to do that by checking the day difference between the 2 array values and then counting & displaying the days. However, I am not sure how to do this dynamically between the 2 array values.
Here's the code I have used along with the output:
//id of the person updating the DSR
$userid = $_id;
// Array to fetch all the DSR by specific user
$fine = getDSRbyUserIdOrderDate($userid);
$today = date('d-m-Y');
$tomorrow = date("d-m-Y", strtotime($today . " +1 day"));
$ok = count($fine) - 1;
//Array to get dates
$d1 = $fine[0]['date'];
$d2 = $fine[1]['date'];
$d3 = $fine[2]['date'];
// Function call to find date difference
$dateDiff = dateDiffInDays($d1, $d2);
$dateDiff1 = dateDiffInDays($d2, $d3);
echo "<h4 style='color:red'>You have missed the DSR on the following dates.</h4>";
for($p = 1; $p < $dateDiff; $p++){
$missingdate = date("d-m-Y", strtotime($d1 . " +$p day"));
echo "<span style='color:red'>$missingdate</span>";
echo "<br />";
}
for($p = 1; $p < $dateDiff1; $p++){
$missingdate = date("d-m-Y", strtotime($d2 . " +$p day"));
echo "<span style='color:red'>$missingdate</span>";
echo "<br />";
}
if($d2 != $today){
echo "<span style='color:red'>$today <i>- Kindly update DSR before midnight</i></span> ";
echo "<br />";
}
Output:
I would create first a list of entries by date and then "paint" it accordingly.
$starting_date = new DateTime('2019-11-23');
$num_days = 10
$from_db_by_date = [];
foreach ($fine as $entry) {
$from_db_by_date[$entry['date']] = $entry;
}
$all_by_date = [];
for ($i = 0; $i < $num_days; $i++) {
$date_str = $starting_date->format('d-m-Y');
$all_by_date[$date_str] = $from_db_by_date[$date_str] ?: null;
$starting_date->modify('+1 day');
}
Now you can loop through $all_by_date, check if the entry is null and act accordingly.
Question:
How the best to convert $p=' "'.implode('","', $person).'"'; $p to an integer?
What I have:
I am trying to use an if statement telling $person == false;
$x['date']; is the timestamp in my database.
I have worked out the time difference, now I am trying to make the person disappear if post over 3 seconds.
so I used $t > 3 seconds then the $p == false;
The difficulty for my was the $t was implode so it a single string. I was trying to use preg_match, but I don't think this is a good idea.
I am trying to use $difference = settype($t, "integer"); but I am getting a boolean rather than a number.
$diff = array();
$person = array();
foreach($stmt as $x)
{
$person[] = $x['names']. $x['ages'];
$posts[] = $x['date'];
$timePosted = new DateTime($posts[] = $x['date']);
echo 'Time Posted : '. $timePosted ->format("d-m-Y H:i:s");
echo "</br>";
date_default_timezone_set('Europe/London');
$today = date('d-m-Y H:i:s');
echo 'Current time is : '. $today;
echo "</br>";
$today = new DateTime(date('d-m-Y H:i:s'));
$interval = $timePosted->diff($today);
"Difference " . $interval->d. " days ". $interval->h. " hours ".$interval->i." minutes ".$interval->s." seconds ";
echo "</br>";
$diff[] = $interval->h. " hours ".$interval->i." minutes ".$interval->s." seconds ";
$diff[] = $interval->s; //last array seconds
}
$p=' "'.implode('","', $person).'"';
echo $t= ' "'.implode('","', $diff).'"'."<br />";
$difference = settype($t, "integer");
echo gettype($difference);
echo "</br>";
if( $t >3){
$p == false;
}else{
echo "its okay, smaller than 3 seconds";
}
The problem is you're setting $difference = settype($t, "integer");
The settype function returns a boolean. The value $t should be set to an integer, so to test, use echo gettype($t); instead of echo gettype($difference);
also, you're using a comparison operator instead of the assignment in
if( $t >3){
$p == false;
it should be
if( $t >3){
$p = false;
I have searched through SO but the answers that I've tried doesn't seem to solve my problem.
I have this simple code snippet where the user will input a numeric date, and a month, and the app will return the corresponding Zodiac Sign.
$birthdate = $_POST["birthdate"];
$birthmonth = (ucwords(strtolower($_POST["month"])))
//validations here. . .
$tmp = $birthmonth . " " . $birthdate;
$tmp2 = date_create_from_format('M j', $tmp);
$formatted_dob = date_format($tmp2, 'm-d-Y');
$dob = strtotime($formatted_dob);
echo $formatted_dob;
if ($dob >= strtotime('01-20-2016') && $dob <= strtotime('02-18-2016')) {
echo "Aquarius";
} elseif ($dob >= strtotime('02-19-2016') && $dob <= strtotime('03-20-2016')){
echo "Pisces";
}
Those echo stuff outside the if-else block are working fine, however if I input a value of 25 and February (which later on results to 02-25-2016), it always output Aquarius. How do you compare two strtotimevalues?
I've tried using DateTime object but it only gives me an error, which is another story. Thanks in advance.
Edited:
Change the order of your date (*your format on your date 01-20-2016 m-d-Y that's why when you convert it it becomes 1970-01-01 'Y-m-d' but if you change it into 2016-01-20 'Y-m-d' on your date range the code will work just fine in else-if.
$birthdate = $_POST["birthdate"];
$birthmonth = (ucwords(strtolower($_POST["month"])))
//validations here. . .
$tmp = $birthmonth . " " . $birthdate;
$tmp2 = date_create_from_format('M j', $tmp);
$formatted_dob = date_format($tmp2, 'm-d-Y');
$dob = strtotime($formatted_dob);
echo $formatted_dob;
$dobcompare = date_create(date('m/d/Y', $dob));
$aqstartdate = date_create(date('m/d/Y', strtotime('2016-01-20')));
$aqenddate = date_create(date('m/d/Y', strtotime('2016-02-18')));
$pistartdate = date_create(date('m/d/Y', strtotime('2016-02-19')));
$pienddate = date_create(date('m/d/Y', strtotime('2016-03-20')));
if ($dobcompare >= $aqstartdate && $dobcompare <= $aqenddate) {
echo "Aquarius";
}
elseif ($dobcompare >= $pistartdate && $dobcompare <= $pienddate) {
echo "Pisces";
} else {
echo "IDK";
}
Modify it in your need.
This is the example enter link description here
I have a start date like 07/18/2014, a end date like 07/24/2014, and a period date: every 2 days.
So every 2 days starting by 07/18 i warn the user that something have to do, if is not the right day i warn the user about how left days remaining to the next warning.
How can i do? And if add also time and a period of every 2 hours?
I thought about store first all the dates warning in an array [07-18/2014, 07-20-2014, 07-22-2014, 07/24/2014]
My code is the following but it does not work. Maybe it is not correct like I use strtotime
$endg = strtotime ( "+". $dataupto . " days", strtotime ( $row['startdate'] ) ) ;
$endg = date ( 'Y/m/d' , $endg );
$endgSTR = strtotime($endg);
$tempg = strtotime($row['startdate']);
while( $tempg < $endgSTR){
$arraymonitor[] = strtotime( date($tempgdate ) );
$tempg = $tempg + (strtotime ( " +1 days", $tempg ) );
$arraymonitor[] = $tempg;
echo "</br> tempg in while:";
echo $tempg . " ";
echo "</br> tempg in while 2:";
echo date ( 'Y/m/d' , $tempg ) . "<br/>";
}
I accept also other suggestions!
UPDATE SOLUTION
header( "content-type: text-plain" );
function dayDiff($start, $end){
$timeleft = $end - $start;
$daysleft = round((($timeleft/24)/60)/60);
return $daysleft;
}
function testWarning($today, $end, $delay){
$endDate = strtotime($end);
$warningDate = $endDate;
$todayDate = strtotime($today);
if( $todayDate == $warningDate ){
echo "Oggi c'è un controllo da fare";
}elseif( $todayDate < $warningDate ){
echo "Miss " . dayDiff($todayDate, $warningDate) . " days";
}else{
echo "warning was " . abs(dayDiff($todayDate, $warningDate)) . " giorni fa";
}
echo"\n";
}
$ardata = [07/18/2014, 07/20/2014, 07/22/2014, 07/24/2014];
$today3 = "07/21/2014"; // the day after warning
testWarning( $today3, $end, $delay );
$diffmin = 1000;
for ($i = 0 ; $i<= count($ardata)-1; $i++){
//print_r($ardata);
echo "</br> </br> ardata ";
echo $ardata[$i];
$dataseq = date ( 'm/d/Y' , strtotime($ardata[$i]) );
$diffdata = dayDiff( strtotime($today3), strtotime($dataseq) );
echo "</br></br> DIFFDATA: ";
echo $diffdata;
echo " DIFFMIN ";
echo $diffmin;
if ($diffdata > 0){ // avoiding days before today
if ($diffdata < $diffmin){
$diffmin = $diffdata;
$nextdata = $ardata[$i];
}else{
if ($diffdata == -1){
echo "error array empty";
$nextdata = $today3;
}
}
}else{
echo "monitorterminato";
$nextdata = -1;
}
}
if ($nextdata != -1){
if ($diffmin == 0){ // giorno di oggi quindi avviso
echo "warning WARNING </br> </br>";
}else if ($diffmin > 0 ){
echo " oggi ". $today3." prossimo:". $nextdata. " </br></br>";
testWarning( $today3, $nextdata, $delay );
}else{
// caso errato
echo " </br> </br> ERRORE nel calcolo non può essere negativo";
}
}
Here is an example on how to calculate your warning dates and days left before warning.
<?php
header( "content-type: text-plain" );
$end = "09/18/2014";
$delay = "- 2 days"; // warning will be on 16th
$warningDay = date('m-d-Y', strtotime($delay, strtotime($end)));
echo "Warning is on " . $warningDay . "\n";
$today1 = "09/13/2014"; // 3 days before warning
testWarning( $today1, $end, $delay );
$today2 = "09/16/2014"; // warning day
testWarning( $today2, $end, $delay );
$today3 = "09/17/2014"; // the day after warning
testWarning( $today3, $end, $delay );
function testWarning($today, $end, $delay){
$endDate = strtotime($end);
$warningDate = strtotime($delay, $endDate);
$todayDate = strtotime($today);
echo "today : " . date('m-d-Y', $todayDate) . "->";
if( $todayDate == $warningDate ){
echo "Warning is today";
}elseif( $todayDate < $warningDate ){
echo "Warning in " . dayDiff($todayDate, $warningDate) . " days";
}else{
echo "Warning was " . abs(dayDiff($todayDate, $warningDate)) . " days ago";
}
echo"\n";
}
// $start and $end are timestamps
function dayDiff($start, $end){
$timeleft = $end - $start;
$daysleft = round((($timeleft/24)/60)/60);
return $daysleft;
}
As seen here
$future = strtotime('21 July 2012'); //Future date.
$timefromdb = //source time
$timeleft = $future-$timefromdb;
$daysleft = round((($timeleft/24)/60)/60);
echo $daysleft;