plus Week with PHP Date with GET? - php

I have URL:
http://www.mysite.com/
here is:
$date = new DateTime("2011-11-28");
this show me:
2011-11-28
i would like add for this site buttons PREVIOUS and NEXT.
If i click NEXT then i have url:
http://www.mysite.com/number/2
now this show me:
2011-12-05 //(+ 7 days)
and i have buttons PREVIOUS (http://www.mysite.com/number/1) and NEXT (http://www.mysite.com/next/3)
etc.
How can i modify
$date = new DateTime("2011-11-28");
with $_GET['number'] ? i have modify from 2011-11-28 interval 7 day!

Check out DateTime::modify (available in PHP >= 5.2)
What you want to do is:
// just for checking if nobody is tampering with the number variable:
if (strcspn($_GET['number'], '0123456789') != strlen($_GET['number']) {
die('Invalid input!');
}
// actual calculation:
$amountOfDays = ((int)$_GET['number']) * 7;
$date = new DateTime("2011-11-28");
$date->modify('+'.$amountOfDays.' day');
Alternatively, you can use DateTime::add, but that is only defined in PHP versions >= 5.3.

Use add and sub to add/subtract days.
$date = new DateTime("2011-11-28");
$num = $_GET['number'];
$interval = new DateInterval('P'.$num.'W');
$date->add($interval);
Or, you can use modify
$date = new DateTime("2011-11-28");
$num = $_GET['number'];
$date->modify(($num>0 ? '+' : '').$num.' weeks');

You can also have a look at mktime()
http://php.net/manual/en/function.mktime.php
You can convert the primary date to a timestamp and add 7 days:
$new_date = mktime(0, 0, 0, 11, (28 + intval($_GET['number'])), 2011);
$visible_date = date('Y-m-d', $new_date);
echo $visible_date;

Use:
$date = new DateTime('#'.strtotime( $_GET['number'] . ' week'));
where $_GET['number'] is a natural number.

Try this:
$days = (intval($_GET['number']) - 1) * 7;
$date = new DateTime('2000-01-01');
$date->add(new DateInterval("P$daysD"));

I like strtotime a lot :)
It works like this:
$date = new DateTime("2011-11-28");
$prevWeek = strtotime('-1 week',$date);
$nextWeek = strtotime('+1 week',$date);

Related

PHP DateInterval

I have this function witch return an array of date. I need to jump on every seven days from now until last year.
$date[] = $lastDate = (new \DateTIme('NOW'))->format('Y-m-d');
for ($i = 1; $i < 54; ++$i) { // 54 -> number of weeks in a year
$date[] = $lastDate = date('Y-m-d', strtotime('-7 day', strtotime($lastDate)));
}
return array_reverse($date);
It works but I can do better.
I would like to change it because using 54 for the number of weeks in a year is not very good. (it can change)
So I want to use the DateInterval php class.
I can have the date of the last year with :
$lastYear = date('Y-m-d', strtotime('-1 year', strtotime($lastDate)));
But I don't know how I can have my array with all my dates with the DateInterval class.
Can someone help me? I'm very bad with date manipulation :( ...
Here is an example array about what I need:
["2015-07-06", "2015-07-13", "2015-07-20", "2015-07-27", "2015-08-03", "2015-08-10", "2015-08-17", "2015-08-24", "2015-08-31", "2015-09-07", "2015-09-14", "2015-09-21", "2015-09-28", "2015-10-05", "2015-10-12", "2015-10-19", "2015-10-26", "2015-11-02", "2015-11-09", "2015-11-16", "2015-11-23", "2015-11-30", "2015-12-07", "2015-12-14", "2015-12-21", "2015-12-28", "2016-01-04", "2016-01-11", "2016-01-18", "2016-01-25", "2016-02-01", "2016-02-08", "2016-02-15", "2016-02-22", "2016-02-29", "2016-03-07", "2016-03-14", "2016-03-21", "2016-03-28", "2016-04-04", "2016-04-11", "2016-04-18", "2016-04-25", "2016-05-02", "2016-05-09", "2016-05-16", "2016-05-23", "2016-05-30", "2016-06-06", "2016-06-13", "2016-06-20", "2016-06-27", "2016-07-04"]
PHP got it 's own native DateInterval object. Here 's a short example how to use it.
$oPeriodStart = new DateTime();
$oPeriodEnd = new DateTime('+12 months');
$oPeriod = new DatePeriod(
$oPeriodStart,
DateInterval::createFromDateString('7 days'),
$oPeriodEnd
);
foreach ($oPeriod as $oInterval) {
var_dump($oInterval->format('Y-m-d));
}
So what we 've done here? For a period of dates you need a start date, an end date and the interval. Just test it for yourself. Have fun.
Try this:
$timestamp = strtotime("last Sunday");
$sundays = array();
$last_year_timestamp = strtotime("-1 year ",$timestamp);
while($timestamp >= $last_year_timestamp) {
if (date("w", $timestamp) == 0) {
$sundays[] = date("Y-m-d", $timestamp);
$timestamp -= 86400*7;
continue;
}
$timestamp -= 86400;
}

Calculate budget per week and how many weeks there are left

I want to calculate how many weeks there are left from a specific date to another date, in order to get the budget per week. Here's my code:
$date_from = new DateTime('2015-07-28');
$date_to = new DateTime();
$interval = $date_from->diff($date_to);
$daysleft = ($interval->format('%a') + 1);
$weeksleft = number_format($daysleft / 7);
echo ('3164.49' / $weeksleft);
That code prints 3 167,76 for the last 2 weeks which of course is wrong. But what is wrong with my code?
$date_from = new DateTime('2015-07-28');
$date_to = new DateTime();
$interval = $date_from->diff($date_to);
$daysleft = ($interval->format('%a') + 1);
$weeksleft = number_format($daysleft / 7);
echo (floatval('3164.49') / $weeksleft);
Results
1582.245
You can do it in different way as shown below.
$a = strtotime('2015/07/28');
$b = time();
$diff = abs($a - $b);
echo round($diff/(60*60*24*7)); // to get round figure
try this function,
function datediffInWeeks($date1, $date2)
{
if($date1 > $date2) return datediffInWeeks($date2, $date1);
$first = DateTime::createFromFormat('m/d/Y', $date1);
$second = DateTime::createFromFormat('m/d/Y', $date2);
return floor($first->diff($second)->days/7);
}
var_dump(datediffInWeeks('1/2/2013', '6/4/2013'));// 21
I get 1582.245 .. Check/set your timezone settings.
date_default_timezone_set ($timezone_identifier)
http://php.net/manual/en/timezones.php

last year, this year, next year with php DateTime

I am trying to create a dropbox that will display the last year, the current year and the next year using the php DateTime object.
In my current code I create three objects and have to call a method on 2 of them. This seems a bit heavy on the resources.
$today = new DateTime();
$last_year=new DateTime();
$last_year->sub(new DateInterval('P1Y'));
$next_year = new DateTime();
$next_year->add(new DateInterval('P1Y'));
echo date_format($last_year, 'Y').' '.date_format($today, 'Y').' '.date_format($next_year, 'Y');
another way I found to only use 1 object is
$today = new DateTime();
echo date_format($today->sub(new DateInterval('P1Y')), 'Y').' '.date_format($today->add(new DateInterval('P1Y')), 'Y').' '.date_format($today->add(new DateInterval('P1Y')), 'Y');
but that will become very confusing.
Can someone tell me a better way to do this using DateTime()? As I will need something similar for months ?
Depending upon your version of PHP (>= 5.4), you could tidy it up a bit like this:-
$today = new DateTime();
$last_year=(new DateTime())->sub(new DateInterval('P1Y'));
$next_year = (new DateTime())->add(new DateInterval('P1Y'));
echo $last_year->format('Y').' '.$today->format('Y').' '.$next_year->format('Y');
See it working.
A more readable and concise option may be to use \DateTimeImmutable.
$today = new DateTimeImmutable();
$one_year = new DateInterval('P1Y');
$last_year = $today->sub($one_year);
$next_year = $today->add($one_year);
echo $last_year->format('Y').' '.$today->format('Y').' '.$next_year->format('Y');
See it working.
Other than that, this all looks fine. Worry about optimisation when it is needed.
Try this. This quite efficient.
echo date("Y");
echo date("Y",strtotime("-1 year"));
echo date("Y",strtotime("+1 year"))
May be you can also limit the call of new DateInterval('P1Y') by creating one object and using it for all three calculations?
$interval = new DateInterval('P1Y');
$dateTime = new DateTime();
$lastYear = $dateTime->sub($interval)->format('Y');
$dateTime = new DateTime();
$nextYear = $dateTime->add($interval)->format('Y');
$dateTime = new DateTime();
$thisYear = $dateTime->format('Y');
echo $lastYear . ' ' . $thisYear . ' ' . $nextYear;
and by breaking the single string into multiple commands always helps me in reducing confusions.
<?php
$d = new DateTime('now');
$cy = $d->format('Y');
// Get previous year
$d->modify('-1 year');
$py = $d->format('Y');
//Next year : Since object has previous year, so +2 to get next year
$d->modify('+2 year');
$ny = $d->format('Y');
echo "Previous Year: ".$py."<br>";
echo "Current Year : ".$cy."<br>";
echo "Next Year : ".$ny."<br>";
$d = new DateTime('now');
$cm = $d->format('m');
$d->modify('-1 month');
$pm = $d->format('m');
$d->modify('+2 month');
$nm = $d->format('m');
echo "Previous Month: ".$pm."<br>";
echo "Current Month : ".$cm."<br>";
echo "Next Month : ".$nm."<br>";
?>
Output
Previous Year: 2013
Current Year : 2014
Next Year : 2015
Previous Month: 12
Current Month : 01
Next Month : 02
Just use basic math:
$current = date('Y');
$prev = $current - 1;
$next = $current + 1;
after reading all the answers I came up with this function to create a dropdown box for year.
$name is the name of the
$year_number is the number of years you want to display
this function starts with one year before the current year but you can easily modify it to start displaying from earlier years.
function drop_down_box_date_year(&$dbconn, $name, $year_number){
$today = new DateTime();
$interval = new DateInterval('P1Y');
$startyear = (new DateTime())->sub($interval);
echo '<select name="'.$name.'_year">';
for($i=0;$i<$year_number;$i++){
if($startyear->format('Y')==$today->format('Y')){
echo '<option value="'.$startyear->format('Y').'" selected>'.$startyear->format('Y').'</option>';
}else{
echo '<option value="'.$startyear->format('Y').'">'.$startyear->format('Y').'</option>';
}
$startyear->add($interval);
}
echo'</select>';
}

Calculate Age for PHP 5.2

I am trying to calculate a person's age from their date of birth on an ExpressionEngine site.
The following code works on my local test site but the server is using an older version of PHP (5.2.17) so I amgetting errors.
Could someone suggest what code I would need to use instead?
{exp:channel:entries channel='zoo_visitor'}
<?php
$dob = new DateTime('{member_birthday format='%Y-%m-%d'}');
$now = new DateTime('now');
// This returns a DateInterval object.
$age = $now->diff($dob);
// You can output the date difference however you choose.
echo 'This person is ' .$age->format('%y') .' years old.';
?>
{/exp:channel:entries}
Your current code won't work because DateTime::diff was introduced in PHP 5.3.0.
Normally date arithmetic is quite tricky because you have to take into account timezones, DST and leap years, but for a task as simple as calculating a "whole year" difference you can do it quite easily.
The idea is that the result is equal to the end date's year minus the start date's year, and if the start date's month/day is earlier inside the year than the end date's you should subtract 1 from that. The code:
$dob = new DateTime('24 June 1940');
$now = new DateTime('now');
echo year_diff($now, $dob);
function year_diff($date1, $date2) {
list($year1, $dayOfYear1) = explode(' ', $date1->format('Y z'));
list($year2, $dayOfYear2) = explode(' ', $date2->format('Y z'));
return $year1 - $year2 - ($dayOfYear1 < $dayOfYear2);
}
See it in action. Note how the result increases by 1 on the exact same day as specified for the birthday.
$dob = strtotime('{member_birthday format='%Y-%m-%d'}');
$now = time();
echo 'This person is ' . (1970 - date('Y', ($now - $dob))) .' years old.';
You can use the diff only above PHP 5.3
You can try with modify, it works on 5.2
$age = $now->modify('-' . $dob->format('Y') . 'year');
After much search I have found the answer:
<?php
//date in mm/dd/yyyy format
$birthDate = "{member_birthday format='%m/%d/%Y'}";
//explode the date to get month, day and year
$birthDate = explode("/", $birthDate);
//get age from date or birthdate
$age = (date("md",
date("U",
mktime(0,
0,
0,
$birthDate[0],
$birthDate[1],
$birthDate[2])
)
)
> date("md")
? ((date("Y") - $birthDate[2]) - 1)
: (date("Y") - $birthDate[2]));
echo $age;
?>
The calculations which only use day of year are off by one in some corner cases: They show 1 year for 2012-02-29 and 2011-03-01, while this should be 0 years (and 11 months and 28 days). A possible solution which takes into account leap years is:
<?php
function calculateAge(DateTime $birthDate, DateTime $now = null) {
if ($now == null) {
$now = new DateTime;
}
$age = $now->format('Y') - $birthDate->format('Y');
$dm = $now->format('m') - $birthDate->format('m');
$dd = $now->format('d') - $birthDate->format('d');
if ($dm < 0 || ($dm == 0 && $dd < 0)) {
$age--;
}
return $age;
}
echo calculateAge(new DateTime('2011-04-01'), new DateTime('2012-03-29'));
user579984's solution works, too, though.
$birthday = '1983-03-25';
$cm = date('Y', strtotime($birthday));
$cd = date('Y', strtotime('now'));
$res = $cd - $cm;
if (date('m', strtotime($birthday)) > date('m', strtotime('now')))
$res--;
else if ((date('m', strtotime($birthday)) == date('m', strtotime('now'))) &&
(date('d', strtotime($birthday)) > date('d', strtotime('now'))))
$res--;
echo $res;
I've been using this and it's never let me down. YYYYMMDD being the person's birthday.
$age = floor((date('Ymd') - 'YYYYMMDD') / 10000);
If you want to be more strict you could convert the dates to integers using the intval function or preceding the dates with (int).

Calculating age from date of birth in PHP

What's the most precise function you have come across to work out an age from the users date of birth. I have the following code and was wondering how it could be improved as it doesn't support all date formats and not sure if it's the most accurate function either (DateTime compliance would be nice).
function getAge($birthday) {
return floor((strtotime(date('d-m-Y')) - strtotime($date))/(60*60*24*365.2421896));
}
$birthday = new DateTime($birthday);
$interval = $birthday->diff(new DateTime);
echo $interval->y;
Should work
Check this
<?php
$c= date('Y');
$y= date('Y',strtotime('1988-12-29'));
echo $c-$y;
?>
Use this code to have full age including years, months and days-
<?php
//full age calulator
$bday = new DateTime('02.08.1991');//dd.mm.yyyy
$today = new DateTime('00:00:00'); // Current date
$diff = $today->diff($bday);
printf('%d years, %d month, %d days', $diff->y, $diff->m, $diff->d);
?>
Try using DateTime for this:
$now = new DateTime();
$birthday = new DateTime('1973-04-18 09:48:00');
echo $now->diff($birthday)->format('%y years'); // 49 years
See it in action
This works:
<?
$date = date_create('1984-10-26');
$interval = $date->diff(new DateTime);
echo $interval->y;
?>
If you tell me in what format your $birthday variable comes I will give you exact solution
WTF?
strtotime(date('d-m-Y'))
So you generate a date string from the current timestamp, then convert the date string back into a timestamp?
BTW, one of the reasons it's not working is that strtotime() assumes numeric dates to be in the format m/d/y (i.e. the US format of date first). Another reason is that the parameter ($birthday) is not used in the formula.
Change the $date to $birthday.
For supper accuracy you need to account for the leap year factor:
function get_age($dob_day,$dob_month,$dob_year){
$year = gmdate('Y');
$month = gmdate('m');
$day = gmdate('d');
//seconds in a day = 86400
$days_in_between = (mktime(0,0,0,$month,$day,$year) - mktime(0,0,0,$dob_month,$dob_day,$dob_year))/86400;
$age_float = $days_in_between / 365.242199; // Account for leap year
$age = (int)($age_float); // Remove decimal places without rounding up once number is + .5
return $age;
}
So use:
echo get_date(31,01,1985);
or whatever...
N.B. To see your EXACT age to the decimal
return $age_float
instead.
This function works fine.
function age($birthday){
list($day,$month,$year) = explode("/",$birthday);
$year_diff = date("Y") - $year;
$month_diff = date("m") - $month;
$day_diff = date("d") - $day;
if ($day_diff < 0 && $month_diff==0){$year_diff--;}
if ($day_diff < 0 && $month_diff < 0){$year_diff--;}
return $year_diff;
}
See BLOG Post
Here is my long/detailed version (you can make it shorter if you want):
$timestamp_birthdate = mktime(9, 0, 0, $birthdate_month, $birthdate_day, $birthdate_year);
$timestamp_now = time();
$difference_seconds = $timestamp_now-$timestamp_birthdate;
$difference_minutes = $difference_seconds/60;
$difference_hours = $difference_minutes/60;
$difference_days = $difference_hours/24;
$difference_years = $difference_days/365;

Categories