Wrong output on date - php

if(isset($_POST['submit_event'])){
$m = $_POST['event_month'];
$y = $_POST['event_year'];
$d = $_POST['event_day'];
$date = date('Y-n-d',strtotime($y. '-' .$m. '-' .$d));
echo $date;
//i always get 2013-10-07
}
All my inputted datas are correct although the output is always wrong and the same.

if (isset($_POST['submit_event']) && isset($_POST['event_month']) && isset($_POST['event_year']) && isset($_POST['event_day'])) {
$m = $_POST['event_month'];
$y = $_POST['event_year'];
$d = $_POST['event_day'];
$date_pre = $y. '-' .$m. '-' .$d;
$time = strtotime($date_pre)
$date = date('Y-n-d', $time);
echo $date;
}
// For debugging:
else {
echo "Not all variables have been set."
}

Related

PHP - ask user input for dates and pass to script

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');
}
?>

Check if date is within range in PHP strtotime

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

Php datetime function doesn't recognise dates before 1000

This code is used to take values inputted from a form but this does not take a year entered as 0100 as 0100 but as 1915, this is then used with the JS seen in one of my other questions any help here would be very good, I think the issue is something to do where the year is taken but I just can't get this to work correctly. Is this a limitation of php?
<?php
$year = "";
$month = "";
$day = "";
if (isset($_GET['year']) && !empty($_GET['year'])) {
$year = $_GET['year'];
}
if (isset($_GET['month']) && !empty($_GET['month'])) {
$month = $_GET['month'];
$monthNumber = date('m', strtotime("$month 1 Y"));
}
if (isset($_GET['day']) && !empty($_GET['day'])) {
$day = $_GET['day'];
}
if ($year != "" && $monthNumber != "" && $day != "") {
$fullUrlDate = $year . "-" . $monthNumber . "-" . $day;
$urlDate = new DateTime(date($fullUrlDate));
$today = new DateTime(date("Y-m-d H:i:s"));
$interval = $urlDate->diff($today);
$gapYears = $interval->y;
$gapMonths = $interval->m;
$gapDays = $interval->d;
$gapDaysTotal = $interval->days;
$gapWeeksTotal = round($interval->days/7);
$gapHours = $interval->h;
$gapMinutes = $interval->i;
$gapSeconds = $interval->s;
if ($gapWeeksTotal == 1) {
$gapWeeksSuffix = "";
} else {
$gapWeeksSuffix = "s";
}
if ($gapDays == 1) {
$gapDaysSuffix = "";
} else {
$gapDaysSuffix = "s";
}
$ordinalSuffix = date("S", strtotime($fullUrlDate));
if (strtotime($fullUrlDate) < strtotime(date("Y-m-d H:i:s")) ) {
$dateInThePast = true;
} else {
$dateInThePast = false;
}
// Months gap
$monthsInterval = date_diff($urlDate, $today);
$monthsGap = $monthsInterval->m + ($monthsInterval->y * 12);
$gapMonthsSuffix = ($monthsGap == 1 ? "" : "s");
DateTime has no such limitation, but the date function you use to initialise it, does. You can use DateTime::setDate to set any year you want:
php > $a = new DateTime("2015-08-24");
php > echo $a->format(DateTime::ISO8601);
2015-08-24T00:00:00+0000
php > $a->setDate(90, 8, 24);
php > echo $a->format(DateTime::ISO8601);
0090-08-24T00:00:00+0000
php > $a->setDate(90090, 8, 24);
php > echo $a->format(DateTime::ISO8601);
90090-08-24T00:00:00+0000

PHP Day count function writing

I need to Write a function named countDays which takes a single parameter named dateinstring which is string in the form ”MM.DD.YYY” represent a real date value. The function should print to the console the number of days from the beginning of the year specified in dateInString until the date represented in dateInString. If the value of dateInString is invalid, the function should print ”Bad format” to the console.
I have written the code as below :
function countDays($dateInString){
date_default_timezone_set('America/Los_Angeles');
$date = explode('.', $dateInString);
if(count($date) == 3 && checkdate($date[0], $date[1], $date[2])){
$formatted_date = $date[2].'-'.$date[0].'-'.$date[1].'00:00:00';
$diff = strtotime($formatted_date).'-'.strtotime($date[2].'-01-01 00:00:00');
echo round($diff/86400)+1;
}
else {
echo 'Bad format';
}
};
countDays('1.15.2014');
But the above code seems that not giving the correct output. It is about 33% correct. But where is the problem with this code ? Please help me!!!
$diff = strtotime($formatted_date).'-'.strtotime($date[2].'-01-01 00:00:00');
Change to
$diff = strtotime($formatted_date) - strtotime($date[2].'-01-01 00:00:00');
You made the minus symbol a string instead of an operator.
You could try it this way
function countDays($dateInString) {
date_default_timezone_set('America/Los_Angeles');
$date = explode('.', $dateInString);
if (checkdate($date[0], $date[1], $date[2])) {
$year_start = mktime(0, 0, 0, 1, 1, $date[2]);
$your_date = mktime(0,0,0,$date[0], $date[1], $date[2]);
$diff = $your_date - $year_start;
echo floor($diff /(60*60*24));
} else {
echo "Bad date supplied";
}
}
A better approach would be to use the DateTime class. I haven't included the validation in this, but i suggest you use regex for that.
function countDays($dateInString){
$parts = explode('.', $dateInString);
$date = new DateTime($parts[2] . '-' . $parts[0] . '-' . $parts[1]);
$compare = new DateTime( $date->format('Y') . '-01-01' );
$interval = $date->diff($compare);
return $interval->format('%a');
}
echo countDays('09.15.2014');
Check this out.
function countDays($dateInString){
date_default_timezone_set('America/Los_Angeles');
$date = explode('.', $dateInString);
if(count($date) == 3 && checkdate($date[0], $date[1], $date[2])){
$formatted_date = strtotime($date[2].'/'.$date[0].'/'.$date[1]);
$endTimeStamp = strtotime("2014/01/01");
$timeDiff = abs($endTimeStamp - $formatted_date);
echo round(intval($timeDiff/86400));
}
else {
echo 'Bad format';
}
};
countDays('01.01.2014');

php holidays in calendar error undefined variable

i found some random code on the net and tried using it for my calendar but i keep getting this error:
Notice: Undefined variable: nextHoliday
this error is referring to the code at the end "RETURN $nextHoliday; "
I believe nextHoliday is defined tho so i tried a few things but nothing makes it work.. can someone please help?
Here's the code:
FUNCTION GetTimeStamp($MySqlDate)
{
$date_array = EXPLODE("-",$MySqlDate); // split the array
$var_year = $date_array[0];
$var_month = $date_array[1];
$var_day = $date_array[2];
$var_timestamp = MKTIME(0,0,0,$var_month,$var_day,$var_year);
RETURN($var_timestamp); // return it to the user
} // End function GetTimeStamp()
FUNCTION ordinalDay($ord, $day, $month, $year)
// ordinalDay returns date of the $ord $day of $month.
// For example ordinalDay(3, 'Sun', 5, 2001) returns the
// date of the 3rd Sunday of May (ie. Mother's Day).
//
// Note: $day must be the 3 char abbr. for the day, as
// given by date("D");
//
{
$firstOfMonth = GetTimeStamp("$year-$month-01");
$lastOfMonth = $firstOfMonth + DATE("t", $firstOfMonth) * 86400;
$dayOccurs = 0;
FOR ($i = $firstOfMonth; $i < $lastOfMonth ; $i += 86400)
{
IF (DATE("D", $i) == $day)
{
$dayOccurs++;
IF ($dayOccurs == $ord)
{ $ordDay = $i; }
}
}
RETURN $ordDay;
} // End function ordinalDay()
FUNCTION getNextHoliday()
// Looks through a lists of defined holidays and tells you which
// one is coming up next.
//
{
$year = DATE("Y");
CLASS holiday
{
VAR $name;
VAR $date;
VAR $catNum;
FUNCTION holiday($name, $date, $catNum)
// Contructor to define the details of each holiday as it is created.
{
$this->name = $name; // Official name of holiday
$this->date = $date; // UNIX timestamp of date
$this->catNum = $catNum; // category, we used for databases access
}
} // end class holiday
$holidays[] = NEW holiday("Groundhog Day", GetTimeStamp("$year-2-2"), "20");
$holidays[] = NEW holiday("Valentine's Day", GetTimeStamp("$year-2-14"), "14");
$holidays[] = NEW holiday("St. Patrick's Day", GetTimeStamp("$year-3-17"), "15");
$holidays[] = NEW holiday("Easter", EASTER_DATE($year), "16");
$holidays[] = NEW holiday("Mother's Day", ordinalDay(2, 'Sun', 5, $year), "3");
$holidays[] = NEW holiday("Father's Day", ordinalDay(3, 'Sun', 6, $year), "4");
$holidays[] = NEW holiday("Independence Day", GetTimeStamp("$year-7-4"), "17");
$holidays[] = NEW holiday("Christmas", GetTimeStamp("$year-12-25"), "13");
$numHolidays = COUNT($holidays);
FOR ($i = 0; $i < $numHolidays; $i++)
{
IF ( DATE("z") > DATE("z", $holidays[$i]->date) && DATE("z") <= DATE("z",
$holidays[$i+1]->date) )
{
$nextHoliday["name"] = $holidays[$i+1]->name;
$nextHoliday["dateStamp"] = $holidays[$i+1]->date;
$nextHoliday["dateText"] = DATE("F j, Y", $nextHoliday["dateStamp"]);
$nextHoliday["num"] = $holidays[$i+1]->catNum;
}
}
RETURN $nextHoliday;
} // end function GetNextHoliday
$nextHoliday = getNextHoliday();
ECHO $nextHoliday["name"]." (".$nextHoliday["dateText"].")";
You have one of two options. Either instantiate empty keys for your array values:
$nextHoliday = array();
$nextHoliday['name'] = '';
$nextHoliday['dateStamp'] = '';
$nextHoliday['dateText'] = '';
$nextHoliday['num'] = '';
$numHolidays = COUNT($holidays);
for ($i = 0; $i < $numHolidays; $i++) {
// ... Blah
}
Or use isset before each array lookup:
echo (isset($nextHoliday['name'] ? $nextHoliday['name'] : '') .
" (" .
(isset($nextHoliday) ? $nextHoliday["dateText"] : '' ) .
")";
Nothing better than the ternary operator for inline conditionals.
It's actually good that we're testing this in January, because otherwise this bug would have bitten you later on. The problem is that you are using less than/greater than to determine what the next holiday is. This fails to take into account the last holiday of the last year.
To fix this, the variable $lastHoliday needs to be a negative representation of the last holiday:
$numHolidays = COUNT($holidays);
$nextHoliday = array('name' => '', 'dateStamp' => '', 'dateText' => '', 'num' => '');
for ($i = 0; $i < $numHolidays - 1; $i++) {
$today = DATE("z");
if ($i == 0) {
$lastHoliday = (365 - DATE("z", $holidays[$numHolidays - 1]->date)) * -1;
} else {
$lastHoliday = DATE("z", $holidays[$i]->date);
}
$futureHoliday = DATE("z", $holidays[$i+1]->date);
//print_r($today); echo "<br />";
//print_r($lastHoliday); echo "<br />";
//print_r($futureHoliday); echo "<br />";
if ($today > $lastHoliday && $today <= $futureHoliday ) {
$nextHoliday["name"] = $holidays[$i+1]->name;
$nextHoliday["dateStamp"] = $holidays[$i+1]->date;
$nextHoliday["dateText"] = DATE("F j, Y", $nextHoliday["dateStamp"]);
$nextHoliday["num"] = $holidays[$i+1]->catNum;
}
}
Also consider typing PHP in lowercase, not uppercase, as it is an almost universal standard in PHP. One true brace style wouldn't hurt either.
$nextHoliday is used in a if but is not declared
Declare the variable before the for:
[...]
$nextHoliday = array();
FOR ($i = 0; $i < $numHolidays; $i++)
[...]

Categories