Php datetime function doesn't recognise dates before 1000 - php

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

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

Counting the (year)quarters between two dates

I have project built using laravel and a I have to build a function that counts all the complete quarters that are in the selected date range - the dates used are inserted via input.
Here are the quarters(i used numerical representations for the months)
01 - 03 first quarter
04 - 06 second quarter
07 - 09 third quarter
10 - 12 forth quarter
I would really appreciate your help,because I've been at it for an entire day now and basically have nothing to show for it,i thing I've been trying so hard i'm actually at the point where i'm so tired, i can t think straight.
I do have some code but it;s worthless, because it doesn't work, and any kind of idea or snippet of code is welcomed.
Thanks for your help in advance.
I managed to do this using multiple functions; basically, if this is needed for chart statistics, then a more specific approach might be the case.
I have done this in Laravel with timestamp dates as input (this code can be adapted for getting semesters also :) , it works and is already tested):
public static function getQuartersBetween($start_ts, $end_ts)
{
$quarters = [];
$months_per_year = [];
$years = self::getYearsBetween($start_ts, $end_ts);
$months = self::getMonthsBetween($start_ts, $end_ts);
foreach ($years as $year) {
foreach ($months as $month) {
if ($year->format('Y') == $month->format('Y')) {
$months_per_year[$year->format('Y')][] = $month;
}
}
}
foreach ($months_per_year as $year => $months) {
$january = new Date('01-01-' . $year);
$march = new Date('01-03-' . $year);
$april = new Date('01-04-' . $year);
$june = new Date('01-06-' . $year);
$july = new Date('01-07-' . $year);
$september = new Date('01-09-' . $year);
$october = new Date('01-10-' . $year);
$december = new Date('01-12-' . $year);
if (in_array($january, $months) && in_array($march, $months)) {
$quarter_per_year['label'] = 'T1 / ' . $year;
$quarter_per_year['start_day'] = $january->startOfMonth();
$quarter_per_year['end_day'] = $march->endOfMonth()->endOfDay();
array_push($quarters, $quarter_per_year);
}
if (in_array($april, $months) && in_array($june, $months)) {
$quarter_per_year['label'] = 'T2 / ' . $year;
$quarter_per_year['start_day'] = $april->startOfMonth();
$quarter_per_year['end_day'] = $june->endOfMonth()->endOfDay();
array_push($quarters, $quarter_per_year);
}
if (in_array($july, $months) && in_array($september, $months)) {
$quarter_per_year['label'] = 'T3 / ' . $year;
$quarter_per_year['start_day'] = $july->startOfMonth();
$quarter_per_year['end_day'] = $september->endOfMonth()->endOfDay();
array_push($quarters, $quarter_per_year);
}
if (in_array($october, $months) && in_array($december, $months)) {
$quarter_per_year['label'] = 'T4 / ' . $year;
$quarter_per_year['start_day'] = $october->startOfMonth();
$quarter_per_year['end_day'] = $december->endOfMonth()->endOfDay();
array_push($quarters, $quarter_per_year);
}
}
return $quarters;
}
and getting the years between:
public static function getYearsBetween($start_ts, $end_ts, $full_period = false)
{
$return_data = [];
$current = mktime(0, 0, 0, date('m', $start_ts), date('d', $start_ts), date('Y', $start_ts));
while ($current < $end_ts) {
$temp_date = $current;
$year = new Date($temp_date);
$return_data[] = $year;
$current = strtotime("+1 year", $current); // add a year
}
if ($full_period) {
$return_data[] = $end_ts;
}
return $return_data;
}
, also getting the months needed
public static function getMonthsBetween($start_ts, $end_ts, $full_period = false)
{
$return_data = $month_list = [];
$current = mktime(0, 0, 0, date('m', $start_ts), date('d', $start_ts), date('Y', $start_ts));
while ($current <= $end_ts) {
$temp_date = $current;
$date = new Date($temp_date);
$month_list[] = $date;
$current = strtotime("+1 month", $current); // add a month
}
$start_date_last_month = new Date(array_first($month_list));
$start_date_last_month = $start_date_last_month->startOfMonth()->format('m-d');
$temp_end_date = new Date($start_ts);
$temp_end_date = $temp_end_date->format('m-d');
if ($start_date_last_month < $temp_end_date) {
array_shift($month_list);
}
$end_date_last_month = new Date(end($month_list));
$current_day_month = $end_date_last_month->endOfMonth()->format('m-d');
$temp_end_date = new Date($end_ts);
$end_day_of_month = $temp_end_date->format('m-d');
if ($end_day_of_month < $current_day_month) {
array_pop($month_list);
}
if (count($month_list) == 0) {
$month_list[] = $end_date_last_month->subMonth();
}
$return_data = $month_list;
if ($full_period) {
$return_data[] = $end_ts;
}
return $return_data;
}
You can do something like in this example:
$February = 2;
$October = 10;
$completedQuarters = ceil($October/3) - ceil($February/3); // = 3
What about the quarter in which the date range starts, should it also count? If it should only count if it begins in the first month of a quarter you can check for it like this:
$completedQuarters = ceil($October/3) - ceil($February/3) -1; // = 2
if($February-1%3 == 0) $completedQuarters += 1;
You´re description is not very clear, let me know if that´s what you had in mind.
Not sure if the following is what you are meaning but might be useful
$date_start='2015/03/12';
$date_end='2017/11/14';
$timezone=new DateTimeZone('Europe/London');
$start=new DateTime( $date_start, $timezone );
$end=new DateTime( $date_end, $timezone );
$difference = $end->diff( $start );
$months = ( ( $difference->format('%y') * 12 ) + $difference->format('%m') );
$quarters = intval( $months / 3 );
printf( 'Quarters between %s and %s is %d covering %d months', $start->format('l, jS F Y'), $end->format('l, jS F Y'), $quarters, $months );
/*
This will output
----------------
Quarters between Thursday, 12th March 2015 and Tuesday, 14th November 2017 is 10 covering 32 months
*/
Something like this in the function and you should be set.
use Carbon\Carbon;
$first = Carbon::parse('2012-1-1'); //first param
$second = Carbon::parse('2014-9-15'); //second param
$fY = $first->year; //2012
$fQ = $first->quarter; //1
$sY = $second->year; //2014
$sQ = $second->quarter; //3
$n = 0; //the number of quarters we have counted
$i = 0; //an iterator we will use to determine if we are in the first year
for ($y=$fY; $y < $sY; $y++, $i++) { //for each year less than the second year (if any)
$s = ($i > 0) ? 1 : $fQ; //determine the starting quarter
for ($q=$s; $q <= 4; $q++) { //for each quarter
$n++; //count it
}
}
if ($sY > $fY) { //if both dates are not in the same year
$n = $n + $sQ; //total is the number of quarters we've counted plus the second quarter value
} else {
for ($q=$fQ; $q <= $sQ; $q++) { //for each quarter between the first quarter and second
$n++; //count it
}
}
print $n; //the value to return (11)

Start counting weeks from specific month

Im trying to write php code which would start counting weeks from specific month. For me its September and February. For example desired result for 01.09.2017 would be Semester-1,Week-1. and for 04.09.2017 would be Semester-1,Week-2. I found similar topics here and here . But their output result is array, should i work with arreys here too ? I want to mention that I almost have zero expierence with php language.
This is what I have come up with so far:
<?php
$day = date("D");
$month = date("M");
if($month == 'Apr'||'Feb'||'Mar'||'May') {
print "Semester-2,";
}
else print "";
if($month == 'Sep'||'Oct'||'Nov'||'Dec') {
print "Semester-1,";
}
else print "";
if($month == 'Jan') {
print "Exams";
}
if($month == 'Jun') {
print "Exams,";
}
if($month == 'Jun') {
print "Exams,";
}
if($month == 'Jul'||'Aug') {
print "Summer Break,";
}
You could do something like this:
$month = date('n'); // Month number 1-12
if ($month >= 9 && $month <=12) {
$period = 'Semester-1';
$startWeek = date('W', strtotime(date('Y') . '-09-01'));
} elseif ($month >= 2 && $month <=5) {
$period = 'Semester-2';
$startWeek = date('W', strtotime(date('Y') . '-02-01'));
} elseif ($month == 1) {
$period = 'Exams';
$startWeek = date('W', strtotime(date('Y') . '-01-01'));
} elseif ($month == 6) {
$period = 'Exams';
$startWeek = date('W', strtotime(date('Y') . '-06-01'));
} elseif ($month == 7 || $month == 8) {
$period = 'Summer break';
$startWeek = date('W', strtotime(date('Y') . '-07-01'));
}
$currentWeek = date('W') - $startWeek + 1;
echo $period . ' ' . 'Week-' . $currentWeek;
After #Qirel comment, I thought of something like this, hope this helps :
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
$month = date("M"); /* current month */
if (in_array($month, array("Sep", "Oct", "Nov", "Dec"))) { $myperiod = "Semester #1"; }
if (in_array($month, array("Feb", "Mar", "Apr", "May"))) { $myperiod = "Semester #2"; }
if($month == 'Jan') { $myperiod = "Mid-Exams #1"; }
if($month == 'Jun') { $myperiod = "Final-Exams #2"; }
if( ($month == 'Jul') || ($month == 'Aug') ) { $myperiod = "Summer break"; }
$today = date("Y-m-d"); /* or use your date from user data */
$date = new DateTime($today);
$week = $date->format("W"); /* use of PHP function 'date' to get week # */
$currentweek = "$week";
echo "[ Week # $week ]";
echo"You currently are in : $myperiod - $currentweek";
?>
This should give you what you need:
$semesters = array(
'Sep' => 'Semester-1',
'Oct' => 'Semester-1',
'Nov' => 'Semester-1',
'Dec' => 'Semester-1',
'Jan' => 'Exams',
'Feb' => 'Semester-2',
'Mar' => 'Semester-2',
'Apr' => 'Semester-2',
'May' => 'Semester-2',
'Jun' => 'Exams',
'Jul' => 'Summer Break',
'Aug' => 'Summer Break',
);
switch ($semesters[date('M')]) {
case 'Semester-1':
$sep1st = strtotime('2017-09-01');
$week1 = date('W', $sep1st);
$currentWeek = date('W');
echo 'Semester-1, Week-', $currentWeek - $week1 + 1; // +1 because the count starts at 1.
break;
case 'Semester-2':
$feb1st = strtotime('2018-02-01');
$week1 = date('W', $feb1st);
$currentWeek = date('W');
echo 'Semester-2, Week-', $currentWeek - $week1 + 1; // +1 because the count starts at 1.
break;
default:
echo $semesters[date('M')];
break;
}
Note that this can be refactored into smaller, more semantic parts.

Wrong output on date

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."
}

PHP add 1 month to date

I've a function that returns url of 1 month before.
I'd like to display current selected month, but I cannot use simple current month, cause when user clicks link to 1 month back selected month will change and will not be current.
So, function returns August 2012
How do I make little php script that adds 1 month to that?
so far I've:
<?php echo strip_tags(tribe_get_previous_month_text()); ?>
simple method:
$next_month = strtotime('august 2012 next month');
better method:
$d = new Date('August 2012');
$next_month = $d->add(new DateInterval('P1M'));
relevant docs: strtotime date dateinterval
there are 3 options/answers
$givendate is the given date (ex. 2016-01-20)
option 1:
$date1 = date('Y-m-d', strtotime($givendate. ' + 1 month'));
option 2:
$date2 = date('Y-m-d', strtotime($givendate. ' + 30 days'));
option 3:
$number = cal_days_in_month(CAL_GREGORIAN, date('m', strtotime($givendate)), date('Y', strtotime($givendate)));
$date3 = date('Y-m-d', strtotime($date2. ' + '.$number.' days'));
You can with the DateTime class and the DateTime::add() method:
Documentation
You can simple use the strtotime function on whatever input you have to arrive at April 2012 then apply the date and strtotime with an increment period of '+1 month'.
$x = strtotime($t);
$n = date("M Y",strtotime("+1 month",$x));
echo $n;
Here are the relevant sections from the PHP Handbook:
http://www.php.net/manual/en/function.date.php
https://secure.php.net/manual/en/function.strtotime.php
This solution solves the additional issue of incrementing any amount of time to a time value.
Hi In Addition to their answer. I think if you just want to get the next month based on the current date here's my solution.
$today = date("Y-m-01");
$sNextMonth = (int)date("m",strtotime($today." +1 months") );
Notice That i constantly define the day to 01 so that we're safe on getting the next month. if that is date("Y-m-d"); and the current day is 31 it will fail.
Hope this helps.
Date difference
$date1 = '2017-01-20';
$date2 = '2019-01-20';
$ts1 = strtotime($date1);
$ts2 = strtotime($date2);
$year1 = date('Y', $ts1);
$year2 = date('Y', $ts2);
$month1 = date('m', $ts1);
$month2 = date('m', $ts2);
echo $joining_months = (($year2 - $year1) * 12) + ($month2 - $month1);
Since we know that strtotime(+1 month) always adds 30 days it can be some troubles with dates ending with the day 31, 30 or 29 AND if you still want to stay within the last day of the next month.
So I wrote this over complicated script to solve that issue as well as adapting so that you can increase all type of formats like years, months, days, hours, minutes and seconds.
function seetime($datetime, $p = '+', $i, $m = 'M', $f = 'Y-m-d H:i:s')
{
/*
$datetime needs to be in format of YYYY-MM-DD HH:II:SS but hours, minutes and seconds are not required
$p can only be "+" to increse or "-" to decrese
$i is the amount you want to change
$m is the type you want to change
Allowed types:
Y = Year
M = Months
D = Days
W = Weeks
H = Hours
I = Minutes
S = Seconds
$f is the datetime format you want the result to be returned in
*/
$validator_y = substr($datetime,0,4);
$validator_m = substr($datetime,5,2);
$validator_d = substr($datetime,8,2);
if(checkdate($validator_m, $validator_d, $validator_y))
{
$datetime = date('Y-m-d H:i:s', strtotime($datetime));
#$p = either "+" to add or "-" to subtract
if($p == '+' || $p == '-')
{
if(is_int($i))
{
if($m == 'Y')
{
$year = date('Y', strtotime($datetime));
$rest = date('m-d H:i:s', strtotime($datetime));
if($p == '+')
{
$ret = $year + $i;
}
else
{
$ret = $year - $i;
}
$str = $ret.'-'.$rest;
return(date($f, strtotime($str)));
}
elseif($m == 'M')
{
$year = date('Y', strtotime($datetime));
$month = date('n', strtotime($datetime));
$rest = date('d H:i:s', strtotime($datetime));
$his = date('H:i:s', strtotime($datetime));
if($p == '+')
{
$ret = $month + $i;
$ret = sprintf("%02d",$ret);
}
else
{
$ret = $month - $i;
$ret = sprintf("%02d",$ret);
}
if($ret < 1)
{
$ret = $ret - $ret - $ret;
$years_back = floor(($ret + 12) / 12);
$monts_back = $ret % 12;
$year = $year - $years_back;
$month = 12 - $monts_back;
$month = sprintf("%02d",$month);
$new_date = $year.'-'.$month.'-'.$rest;
$ym = $year.'-'.$month;
$validator_y = substr($new_date,0,4);
$validator_m = substr($new_date,5,2);
$validator_d = substr($new_date,8,2);
if(checkdate($validator_m, $validator_d, $validator_y))
{
return (date($f, strtotime($new_date)));
}
else
{
$days = date('t',strtotime($ym));
$new_date = $ym.'-'.$days.' '.$his;
return (date($f, strtotime($new_date)));
}
}
if($ret > 12)
{
$years_forw = floor($ret / 12);
$monts_forw = $ret % 12;
$year = $year + $years_forw;
$month = sprintf("%02d",$monts_forw);
$new_date = $year.'-'.$month.'-'.$rest;
$ym = $year.'-'.$month;
$validator_y = substr($new_date,0,4);
$validator_m = substr($new_date,5,2);
$validator_d = substr($new_date,8,2);
if(checkdate($validator_m, $validator_d, $validator_y))
{
return (date($f, strtotime($new_date)));
}
else
{
$days = date('t',strtotime($ym));
$new_date = $ym.'-'.$days.' '.$his;
return (date($f, strtotime($new_date)));
}
}
else
{
$ym = $year.'-'.$month;
$new_date = $year.'-'.$ret.'-'.$rest;
$validator_y = substr($new_date,0,4);
$validator_m = substr($new_date,5,2);
$validator_d = substr($new_date,8,2);
if(checkdate($validator_m, $validator_d, $validator_y))
{
return (date($f, strtotime($new_date)));
}
else
{
$ym = $validator_y . '-'.$validator_m;
$days = date('t',strtotime($ym));
$new_date = $ym.'-'.$days.' '.$his;
return (date($f, strtotime($new_date)));
}
}
}
elseif($m == 'D')
{
return (date($f, strtotime($datetime.' '.$p.$i.' days')));
}
elseif($m == 'W')
{
return (date($f, strtotime($datetime.' '.$p.$i.' weeks')));
}
elseif($m == 'H')
{
return (date($f, strtotime($datetime.' '.$p.$i.' hours')));
}
elseif($m == 'I')
{
return (date($f, strtotime($datetime.' '.$p.$i.' minutes')));
}
elseif($m == 'S')
{
return (date($f, strtotime($datetime.' '.$p.$i.' seconds')));
}
else
{
return 'Fourth parameter can only be any of following: Valid Time Parameters Are: Y M D Q H I S';
}
}
else
{
return 'Third parameter can only be a number (whole number)';
}
}
else
{
return 'Second parameter can only be + to add or - to subtract';
}
}
else
{
return 'Date is not a valid date';
}
}

Categories