Year and week to date in php - php

I have two pieces of information extracted from a MySQL database, the year(2009, 2010, ect) and the week (1-52). And I need to convert it in to a date start and date end..
For example:
Year=2010, Week=1 would be (Friday, Jan 1st, 2010) - (Sunday, Jan 3rd, 2010)
Year=2010, Week=33 would be (Monday, Aug 16th, 2010) - (Sunday, Aug 22nd, 2010)
Year=2010, Week=34 would be (Monday, Aug 23rd, 2010) - (Sunday, Aug 29th, 2010)
How would I go about doing that in php ?

$year = "2010"; // Year 2010
$week = "01"; // Week 1
$date1 = date( "l, M jS, Y", strtotime($year."W".$week."1") ); // First day of week
$date2 = date( "l, M jS, Y", strtotime($year."W".$week."7") ); // Last day of week
echo $date1 . " - " . $date2;
If week number is under 10 then append a 0 before number. 1 won't work, it should be 01.

Since this question and the accepted answer were posted the DateTime classes make this much simpler to do:-
function daysInWeek($weekNum)
{
$result = array();
$datetime = new DateTime();
$datetime->setISODate((int)$datetime->format('o'), $weekNum, 1);
$interval = new DateInterval('P1D');
$week = new DatePeriod($datetime, $interval, 6);
foreach($week as $day){
$result[] = $day->format('d/m/Y');
}
return $result;
}
var_dump(daysInWeek(24));
Output:-
array (size=7)
0 => string '10/06/2013' (length=10)
1 => string '11/06/2013' (length=10)
2 => string '12/06/2013' (length=10)
3 => string '13/06/2013' (length=10)
4 => string '14/06/2013' (length=10)
5 => string '15/06/2013' (length=10)
6 => string '16/06/2013' (length=10)
This has the added advantage of taking care of leap years etc..

function getStartAndEndDate($week, $year)
{
//setting the default time zone
date_default_timezone_set('America/New_York');
//getting the
//$firstWeek = date('W',strtotime("January 1 $year", date(time())));
//echo "Year : ".$year."<br/>"."Week : ".$week."<br/>";
$firstWeekThursDay = date('W',strtotime("January $year first thursday",date(time())));
if($firstWeekThursDay == "01")
{
$time = strtotime("January $year first thursday",date(time()));
//echo $time."<br/>";
//echo date('Y-m-d H:i:s',$time)."<br/>";
$time = ($time-(4*24*3600))+(((7*$week)-6)*24*3600);
//echo $time."<br/>";
//echo date('Y-m-d H:i:s',$time)."<br/>";
$return[0] = date('Y-m-d', $time);
$time += 6*24*3600;
$return[1] = date('Y-m-d', $time);
//print_r($return);
}
else
{
$time = strtotime("January 1 $year", time());
//echo "<br/>".$time."<br/>";
//echo date('Y-m-d H:i:s',$time)."<br/>";
$time = ($time-(4*24*3600))+(((7*$week)-6)*24*3600);
//echo $time."<br/>";
//echo date('Y-m-d H:i:s',$time)."<br/>";
$return[0] = date('Y-m-d', $time);
$time += 6*24*3600;
$return[1] = date('Y-m-d', $time);
//print_r($return);
//echo "<br/>End of Hi<br/>";
}
return $return;
}

Try this out:
$year = 2000;
$week = 1;
$start = date("l, M jS, Y", strtotime("01 Jan ".$year." 00:00:00 GMT + ".$week." weeks"));
$end = date("l, M jS, Y", strtotime($start." + 1 week"));
echo $start." to ".$end;
You need to set $year and $week. It will then print the interval as specified.
For instance, the output as-is is:
Friday, Jan 7th, 2000 to Friday, Jan 14th, 2000
Note that weeks are indexed from 0-51 (easy to fix).
It's kind of ugly, but it works. Hope that helps!

Related

PHP: strtotime() gives wrong output

In my script, I have a given end date. To get the start date, I subtract 23 months to the end date. Basically, what my script should do is to output 24 months (w/ year) - the last month/year to be printed should always be the specified end date.
For some reason, my script isn't returning my desired results. Given the $end = '2013-07-05', the script returns the result correctly. It prints out Aug 11 to Jul 13 which is correct.
But for some dates (e.g. $end = '2013-07-31'), the output is wrong. The result should be Sep 11 to Aug 13. But in this case, it outputs Aug 11 to Aug 13 which is absolutely wrong.
Here's my code:
<?php
$end = strtotime('2013-07-31 +1 month');
$date = strtotime('2013-07-31 -23 month');
$start = $month = $date;
$months = "";
while($month < $end)
{
$months .= date('M y', intval($month))." ";
$month = strtotime("+1 month", intval($month));
}
echo $months;
?>
I think there's something wrong with strtotime(). Thanks in advance.
You can't really use month calculations like that, especially when dealing with end-of-month values:
e.g. if it's July 31, what's -1 month to strtotime?
php > echo date('r', strtotime('2013-07-31 -1 month'));
Mon, 01 Jul 2013 00:00:00 -0600
A human would probably pick out June 30th, but strtotime isn't human. This DOES work for February 28th and generally any date where the day value is <= 28. Once you get into the 29,30,31 area, then you get these unexepected results
php > echo date('r', strtotime('2013-04-28 -1 month'));
Thu, 28 Mar 2013 00:00:00 -0600
How about
$endMonth = '8';
$year = '2013';
$i = 24;
while( $i > 0 ){
$month = ($endMonth - $i)%12;
if( $month == 0 ){
$year = $year - 1;
$month = 12;
}
$months .= date('M y', strtotime($year.'-'.$month.'-02'));
$i--;
}
Based on Marc B's answer I modified the script to deal with the 29,30,31 of each month. What I did was, if the date is 29, 30, or 31, it will be subtracted with 3 days so that the date will be either 28 or below and would work just fine with the current code that I have. It worked for me so I guess I'll just stick with this for now. Here's the updated code:
<?php
$dt = "2013-07-31";
$dy = strtotime($dt);
$day = date("d", $dy);
if (($day == 29) || ($day == 30) || ($day == 31)){
$dt = strtotime("$dt -3 days");
$dt = date('Y-m-d', $dt);
}
$end = strtotime("$dt +1 month");
$date = strtotime("$dt -23 month");
$start = $month = $date;
$months = "";
while($month < $end)
{
$months .= date('M y', intval($month))." ";
$month = strtotime("+1 month", intval($month));
}
echo $months;
?>
Thanks for your help and insights. :)

PHP date add 5 year to current date

I have this PHP code:
$end=date('Y-m-d');
I use it to get the current date, and I need the date 5 years in the future, something like:
$end=date('(Y + 5)-m-d');
How can I do this?
Try with:
$end = date('Y-m-d', strtotime('+5 years'));
Modifying dates based on this post
strtotime() is really powerful and allows you to modify/transform dates easily with it’s relative expressions too:
Procedural
$dateString = '2011-05-01 09:22:34';
$t = strtotime($dateString);
$t2 = strtotime('-3 days', $t);
echo date('r', $t2) . PHP_EOL; // returns: Thu, 28 Apr 2011 09:22:34 +0100
DateTime
$dateString = '2011-05-01 09:22:34';
$dt = new DateTime($dateString);
$dt->modify('-3 days');
echo $dt->format('r') . PHP_EOL; // returns: Thu, 28 Apr 2011 09:22:34 +0100
The stuff you can throw at strtotime() is quite surprising and very human readable. Have a look at this example looking for Tuesday next week.
Procedural
$t = strtotime("Tuesday next week");
echo date('r', $t) . PHP_EOL; // returns: Tue, 10 May 2011 00:00:00 +0100
DateTime
$dt = new DateTime("Tuesday next week");
echo $dt->format('r') . PHP_EOL; // returns: Tue, 10 May 2011 00:00:00 +0100
Note that these examples above are being returned relative to the time now.
The full list of time formats that strtotime() and the DateTime constructor takes are listed on the PHP Supported Date and Time Formats page.
Another example, suitable for your case could be: based on this post
<?php
//How to get the day 3 days from now:
$today = date("j");
$thisMonth = date("n");
$thisYear = date("Y");
echo date("F j Y", mktime(0,0,0, $thisMonth, $today+3, $thisYear));
//1 week from now:
list($today,$thisMonth,$thisYear) = explode(" ", date("j n Y"));
echo date("F j Y", mktime(0,0,0, $thisMonth, $today+7, $thisYear));
//4 months from now:
list($today,$thisMonth,$thisYear) = explode(" ", date("j n Y"));
echo date("F j Y", mktime(0,0,0, $thisMonth+4, $today, $thisYear));
//3 years, 2 months and 35 days from now:
list($today,$thisMonth,$thisYear) = explode(" ", date("j n Y"));
echo date("F j Y", mktime(0,0,0, $thisMonth+2, $today+35, $thisYear+3));
?>
Use this code to add years or months or days or hours or minutes or seconds to a given date
echo date("Y-m-d H:i:s", strtotime("+1 years", strtotime('2014-05-22 10:35:10'))); //2015-05-22 10:35:10
echo date("Y-m-d H:i:s", strtotime("+1 months", strtotime('2014-05-22 10:35:10')));//2014-06-22 10:35:10
echo date("Y-m-d H:i:s", strtotime("+1 days", strtotime('2014-05-22 10:35:10')));//2014-05-23 10:35:10
echo date("Y-m-d H:i:s", strtotime("+1 hours", strtotime('2014-05-22 10:35:10')));//2014-05-22 11:35:10
echo date("Y-m-d H:i:s", strtotime("+1 minutes", strtotime('2014-05-22 10:35:10')));//2014-05-22 10:36:10
echo date("Y-m-d H:i:s", strtotime("+1 seconds", strtotime('2014-05-22 10:35:10')));//2014-05-22 10:35:11
You can also subtract replacing + to -
$date = strtotime($row['timestamp']);
$newdate = date('d-m-Y',strtotime("+1 year",$date));
Its very very easy with Carbon.
$date = "2016-02-16"; // Or Your date
$newDate = Carbon::createFromFormat('Y-m-d', $date)->addYear(1);
Using Carbon:
$dt = Carbon::now();
echo $dt->addYears(5);
To add one year to todays date use the following:
$oneYearOn = date('Y-m-d',strtotime(date("Y-m-d", mktime()) . " + 365 day"));
You may use DateInterval for this purpose;
$currentDate = new \DateTime(); //creates today timestamp
$currentDate->add(new \DateInterval('P5Y')); //this means 5 Years
and you can now format it;
$currentDate->format('Y-m-d');
Try below code, i hope it will be helpful for you
<?php
$current_date=strtotime(date('Y-m-d'));
echo $end = date('Y-m-d', strtotime('+5 years',$current_date));
?>
try this ,
$presentyear = '2013-08-16 12:00:00';
$nextyear = date("M d,Y",mktime(0, 0, 0, date("m",strtotime($presentyear )), date("d",strtotime($presentyear )), date("Y",strtotime($presentyear ))+5));
echo $nextyear;
try this:
$yearnow= date("Y");
$yearnext=$yearnow+1;
echo date("Y")."-".$yearnext;
Try this code and add next Days, Months and Years
// current month: Aug 2018
$n = 2;
for ($i = 0; $i <= $n; $i++){
$d = strtotime("$i days");
$x = strtotime("$i month");
$y = strtotime("$i year");
echo "Dates : ".$dates = date('d M Y', "+$d days");
echo "<br>";
echo "Months : ".$months = date('M Y', "+$x months");
echo '<br>';
echo "Years : ".$years = date('Y', "+$y years");
echo '<br>';
}

PHP find closest specific day to date

I'm writing a script that gets some statistics about my website for a date this year, but I also want it to get me the data for the nearest corresponding day last year so I can compare them.
For example if I were to get the data for "Wednesday 14th Dec 2011", I'd want to also get the data for "Wednesday 15th Dec 2010".
I'm having a bit of trouble thinking of how to get the correct date from this year's date. I'd prefer to be able to pass the data into a function, something like:
// $date as a unix timestamp
// $day (0 for Sunday through 6 for Saturday)
function getClosestDay($date,$day=0) {
}
So I would be passing in a unix timestamp of last year's date, and also the day I'm looking to find. I'd expect it to return a unix timestamp of the correct day.
But I'm not sure where to even start with the function.
I'm not looking for someone to write the function for me, but if anyone has any ideas on where to start (even a nudge in the right direction) then that would be great!
I believe this would do. First we get the unix time of the same day last year
$newDate = '14th Dec 2011';
$newDate = strtotime($newDate);
$oldDate = strtotime('-1 year',$newDate);
Now we find the difference in week day. In this example, it'll be -1
$newDayOfWeek = date('w',$oldDate);
$oldDayOfWeek = date('w',$newDate);
$dayDiff = $oldDayOfWeek-$newDayOfWeek;
And then we extract/add that difference to the date
$oldDate = strtotime("$dayDiff days",$oldDate);
And output it
print date('r',$oldDate)."\n";
print date('r',$newDate)."\n";
The above should yield
Wed, 15 Dec 2010 00:00:00 +0100
Wed, 14 Dec 2011 00:00:00 +0100
Here is what I came up with:
function getClosestDate($date, $day = 0, $year = -1) {
$cts = strtotime($date);
$ts = strtotime("{$year} YEAR", $cts);
$days = array(
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
);
$day = $days[$day];
$prev = strtotime("PREVIOUS {$day}", $ts);
$next = strtotime("NEXT {$day}", $ts);
$prev_gap = $ts - $prev;
$next_gap = $next - $ts;
return $prev_gap < $next_gap ? $prev : $next;
}
echo date('Y-m-d', getClosestDate('2011-12-12', 1));
// prints 2010-12-13 (closest Monday to 2010-12-12)
echo date('Y-m-d', getClosestDate('2011-12-12', 4));
// prints 2010-12-09 (closest Thursday to 2010-12-12)
And by the way (and fortunately), December 14th 2011 is not a Monday. :)
I got it, here it goes:
function getClosestDay($date) {
$w = date("w", strtotime("-1 year", $date));
$week = date("w", $date);
$days = ($week - $w);
return date("Y-m-d l", strtotime($days . " days -1 year", $date));
}
echo getClosestDay(mktime(0, 0, 0, 12, 14, 2011));
Try this
function getClosestDay($date,$day=0) {
$days = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
return strtotime('last ' . $days[$day], $date);
}
Here is a less elegant but tested function :
function getClosestDay($time,$dayOfTheWeek) {
$last_year=strtotime("last year",$time);
$next=strtotime("next $dayOfTheWeek",$last_year);
$last=strtotime("previous $dayOfTheWeek",$last_year);
$most_near = (min($next-$last_year,$last_year-$last) == ($next-$last_year)) ? $next : $last;
return $most_near;
}
Have you tried strtotime?
strtotime('-1 year',time());

PHP - Date function - finding the previous week

In my application a week is defined from Monday 12:00:00 AM to Sunday 11:59:59 PM
Whenever a user visits my site - I need to find the previous weeks date range and show him results based on that. It sounds simple but I'm lost.
To give you scenarios -
- March 1st Monday 12:00:00 AM to March 7th Sunday 12:59:59 PM is the week.
Now when a user visits the website on 8th March or 10th March or 12th March - based on the current date I should be able to get the previous week date range ie start date March 1st and end date March 7th.
But if the user visits the site say on 16th March - the date range I would need is March 8th to March 15th.
How can I do this in PHP.
Thanks
You could try doing it with timestamps, but that gets messy with timezone changes (for example, CET -> CEST). I'd use the DateTime class:
$d = new DateTime();
$weekday = $d->format('w');
$diff = 7 + ($weekday == 0 ? 6 : $weekday - 1); // Monday=0, Sunday=6
$d->modify("-$diff day");
echo $d->format('Y-m-d') . ' - ';
$d->modify('+6 day');
echo $d->format('Y-m-d');
The strtotime function is very handy here:
$mondayStr = "last monday";
if (date('N') !== '1') { // it's not Monday today
$mondayStr .= " last week";
}
$monday = strtotime($mondayStr);
echo date('r', $monday); // Mon, 22 Feb 2010 00:00:00 +1000
$sunday = strtotime('next monday', $monday) - 1;
echo date('r', $sunday); // Sun, 28 Feb 2010 23:59:59 +1000
function get_week_start($year, $month, $day)
{
$timestamp = mktime(0, 0, 0, $month, $day, $year);
return date('F j Y', $timestamp = mktime(0, 0, 0, $month, date('d', $timestamp)-date('w', $timestamp), $year));
}
You could perhaps add the next 6 days and you have it.
There is a user function for this in the PHP Documentation.
GMT version
$prev_monday_t = time() - (gmdate('N') + 6) * 86400;
$prev_sunday_t = time() - gmdate('N') * 86400;
echo gmdate('Y-m-d H:i:s', $prev_monday_t ).' '.gmdate('Y-m-d H:i:s', $prev_sunday_t );
Local version
$prev_monday_t = time() - (date('N') + 6) * 86400;
$prev_sunday_t = time() - date('N') * 86400;
echo date('Y-m-d H:i:s', $prev_monday_t ).' '.date('Y-m-d H:i:s', $prev_sunday_t );

PHP: How to get Sunday and Saturday given a date input?

How can I get the Sunday and Saturday of the week given a specific date?
For example:
input: Monday, September 28, 2009
output should be:
Sunday, September 27, 2009 12:00 AM - Saturday, October 3, 2009 11:59 PM
I am thinking of using the date, strtotime, mktime and time php functions.
If you have a usable function then it is also fine with me.
Thanks in advance :)
Cheers,
Mark
You use strtotime() and date():
<?php
$s = 'Monday, September 28, 2009';
$time = strtotime($s);
$start = strtotime('last sunday, 12pm', $time);
$end = strtotime('next saturday, 11:59am', $time);
$format = 'l, F j, Y g:i A';
$start_day = date($format, $start);
$end_day = date($format, $end);
header('Content-Type: text/plain');
echo "Input: $s\nOutput: $start_day - $end_day";
?>
outputs:
Input: Monday, September 28, 2009
Output: Sunday, September 27, 2009 12:00 PM - Saturday, October 3, 2009 11:59 AM
<?php
date_default_timezone_set('Europe/London');
$datetime = new DateTime("2009-09-23 12:00:00");
// Saturday
$datetime->setISODate(2009, $datetime->format("W"), 6);
print "Saturday:" . $datetime->format(DATE_ATOM) . "\n";
// Sunday
$datetime->setISODate(2009, $datetime->format("W"), 0);
print "Sunday: " . $datetime->format(DATE_ATOM) . "\n";
?>
take a look at strtotime
i.e.
strtotime('next sunday', strtotime($your_date_string));
echo date("Y-m-d H:i:s", strtotime("last sunday", time()));
echo date("Y-m-d H:i:s", strtotime("next saturday", time()));
the issue with the 'correct' answer is, what if the supplied date is Sunday? Then it will give you the previous Sunday, instead of the current Sunday. Same issue with Saturday.
$s = 'Monday, September 28, 2009';
$time = strtotime($s);
if(date('D', $time) == "Sun"){
$start = strtotime(' 12pm', $time);
}
else {
$start = strtotime('last sunday, 12pm', $time);
}
if(date('D', $time) == "Sat"){
$start = strtotime(' 12pm', $time);
}
else {
$start = strtotime('next saturday, 12pm', $time);
}
$format = 'l, F j, Y g:i A';
$start_day = date($format, $start);
$end_day = date($format, $end);
header('Content-Type: text/plain');
echo "Input: $s\nOutput: $start_day - $end_day";
strtotime
$input = strtotime("Monday, September 28, 2009");
$nextSunday = strtotime("next Sunday",$input);
<?php
$date = strtotime('Monday, September 28, 2009 - 1 day');
$initialString = date('l, F d, Y g:i A', $date);
$end = date('l, F d, Y g:i A', strtotime( 'next saturday 11:59 pm', $date));
echo $initialString . ' - ' . $end;
output:
Sunday, September 27, 2009 12:00 AM - Saturday, October 03, 2009 11:59 PM
This is what your looking for. It is what I use.
$beginningOfWeek = date('Y-m-d H:i:s', strtotime('last Sunday'));
$endOfWeek = date('Y-m-d H:i:s', strtotime('+6 day', strtotime('last Sunday')) );
You may find my Date Time Helper much handy in this case , it can finish in 3 Lines
http://normandqq.github.io/Date-Time-Helper/
$date = '2013-08-11';
$monday = Model_DTHpr::getMondayByDate($date);
$sunday = Model_DTHpr::adjustDays("add",$monday,6);
Out Put:
2013-08-05 //Monday
2013-08-11 //Sunday
Get Sunday Php Code:
echo "Today Is : " . date("d-m-Y");
$dw = date( "w");
$dw = 7-$dw;
echo "\nNext Sunday Is" .date('d-m-Y', strtotime("+$dw days"));

Categories