I'd like display dates by week number between giving 2 dates like example below. Is this possible in PHP?
if the dates are 2010-12-01 thru 2010-12-19, it will display it as follows.
week-1
2010-12-01
2010-12-02
2010-12-03
2010-12-04
2010-12-05
2010-12-06
2010-12-07
week-2
2010-12-08
2010-12-09
2010-12-10
2010-12-11
2010-12-12
2010-12-13
2010-12-14
week-3
2010-12-15
2010-12-16
2010-12-17
2010-12-18
2010-12-19
and so on...
I use mysql. It has startdate end enddate fields.
thank you in advance.
I can get how many weeks in those giving 2 dates and display them using a
datediff('ww', '2010-12-01', '2010-12-19', false); I found on the internet.
And I can display dates between two dates as follows. But I am having trouble grouping them by week.
$sdate = "2010-12-01";
$edate = "2010-12-19";
$days = getDaysInBetween($sdate, $edate);
foreach ($days as $val)
{
echo $val;
}
function getDaysInBetween($start, $end) {
// Vars
$day = 86400; // Day in seconds
$format = 'Y-m-d'; // Output format (see PHP date funciton)
$sTime = strtotime($start); // Start as time
$eTime = strtotime($end); // End as time
$numDays = round(($eTime - $sTime) / $day) + 1;
$days = array();
// Get days
for ($d = 0; $d < $numDays; $d++) {
$days[] = date($format, ($sTime + ($d * $day)));
}
// Return days
return $days;
}
New answer.
$current_date = strtotime('2010-12-01');
$end_date = strtotime('2010-12-19');
$day_count = 0;
$current_week = null;
do {
if ((int)($day_count / 7) + 1 != $current_week) {
$current_week = (int)($day_count / 7) + 1;
echo 'week-'.$current_week.'<br />';
}
echo date('Y-m-d', $current_date).'<br />';
$current_date = strtotime('+1 day', $current_date);
$day_count ++;
} while ($current_date <= $end_date);
You will definitely need this: Simplest way to increment a date in PHP?. Write a forloop and increment the day every time. You will also need the DateTime class and functions as date. Indeed asking for date('W', yourDateHere) is a nice idea.
You will get something like this (pseudocode)
$startDate;
$endDate;
$nrOfDays = dateDiffInDays($endDate, $startDate);
$currentWeek = date('W',$startDate);
for($i = 0; $i < $nrOfDays; $i++)
{
$newDay = date('+$i day', $startDate); // get the incremented day
$newWeek = date('W', $newDay); // get the week of the new day
if($newWeek != $currentWeek) // check if we must print the new week, or if we are still in the current
print $newWeek;
print $newDay; // print the day
}
Hope this helps. Good luck.
Tools sufficient to do the job:
strtotime('2010-11-23') - to get a timestamp from a date
strtotime('+1 day', $someTimestamp) - to get the next day
date('W', $someTimestamp) - to get the week number (if you want to group by ISO week number)
array_chunk($orderedListOfSuccessiveDates, 7) - to split in groups of seven days (if you don't want to group by ISO week number)
Warning: Never, ever increment days by adding 86400 to the timestamp! That is the easiest way to break everything when Daylight Saving comes along. Either use the strtotime function or the DateTime class.
Here you go. Although this is with weeks starting on sundays (just change it to monday if need be). And it doesnt work if the dates arent in the same year. But it should be pretty easy to fix that. If not_same_year then ...
$start_date = mktime(0, 0, 0, 12, 01, 2010);
$start_date_week_number = (int) date("W", $start_date);
$end_date = mktime(0, 0, 0, 12, 19, 2010);
$end_date_week_number = (int) date("W", $end_date);
$n = $start_date_week_number;
$w = 1;
$date = $start_date;
while($n <= $end_date_week_number) {
echo("<strong>Week " . $w . "</strong><br />");
$s = 0;
$e = 6;
if($n == $start_date_week_number) $s = (int) date("w", $start_date);
elseif($n == $end_date_week_number) $e = (int) date("w", $end_date);
while($s <= $e) {
echo(date("j-m-y", $date) . "<br />");
$c_date = getdate($date);
$date = mktime($c_date['hours'], $c_date['minutes'], $c_date['seconds'], $c_date['mon'], $c_date['mday'] + 1, $c_date['year']);
$s++;
}
$n++; $w++;
}
DEMO HERE
Edit: just fixed it when I realized you wanted to count the weeks (not get the actual week number)...
$startDate = new DateTime('2010-01-01');
$endDate = new DateTime('2010-01-14');
$weeksDays = getWeeksDaysBetween($startDate, $endDate);
foreach($weeksDays as $week => $days)
{
echo "Week $week<ul>";
foreach($days as $day){
echo "<li>$day</li>";
}
echo "</ul>";
}
function getWeeksDaysBetween($startDate, $endDate)
{
$weeksDays = array();
$dateDiff = $endDate->diff($startDate);
$fullDays = $dateDiff->d;
$numWeeks = floor($fullDays / 7) + 1;
$weeksDays[1][] = $startDate->format('Y-m-d');
for ($i = 1; $i <= $fullDays; $i++)
{
$weekNum = floor($i / 7) + 1;
$dateInterval = DateInterval::createFromDateString("1 day");
$weeksDays[$weekNum][] = $startDate->add($dateInterval)->format('Y-m-d');
}
return $weeksDays;
}
Related
How to enlist all the days between for instance 2018-06-04 and 2018-06-10 that between 2018-06-04 - 2018-06-10 those days will be 2018-06-05, 2018-06-06, 2018-06-07, 2018-06-08, 2018-06-09, the same goes for 2018-06-11 - 2018-06-17 and so on...
So far I'ive managed to divide month into week chunks (below), I want to further divide weeks into days...
2018-06-04 - 2018-06-10
2018-06-11 - 2018-06-17
2018-06-18 - 2018-06-24
2018-06-25 - 2018-07-01
http://zakodowac.pl/
This is my PHP code which produces week chunks above 2018-06-04 - 2018-06-10 and so on...:
function getMondays($y, $m) {
return new DatePeriod(
new DateTime("first monday of $y-$m"),
DateInterval::createFromDateString('next monday'),
new DateTime("last day of $y-$m")
);
}
function list_week_days($year, $month) {
foreach (getMondays($year, $month) as $monday) {
echo $monday->format(" Y-m-d\n");
echo '-';
$sunday = $monday->modify('next Sunday');
echo $sunday->format(" Y-m-d\n");
echo '<br>';
}
}
list_week_days(2018, 06);
could you try this:
$begin = strtotime('2018-06-04');
$end = strtotime('2018-06-10');
while($begin < $end){
$begin = $begin +84600;
echo date('Y-m-d', $begin) . ' ';
}
if correctly understood, then the following should yield the results you expect:
// set current date
$date = '04/30/2009';
// parse about any English textual datetime description into a Unix timestamp
$ts = strtotime($date);
// calculate the number of days since Monday
$dow = date('w', $ts);
$offset = $dow - 1;
if ($offset < 0) {
$offset = 6;
}
// calculate timestamp for the Monday
$ts = $ts - $offset*86400;
// loop from Monday till Sunday
for ($i = 0; $i < 7; $i++, $ts += 86400){
print date("m/d/Y l", $ts) . "\n";
}
if you want to be even more clever, you can use:
// set current date
$date = '04/30/2009';
// parse about any English textual datetime description into a Unix timestamp
$ts = strtotime($date);
// find the year (ISO-8601 year number) and the current week
$year = date('o', $ts);
$week = date('W', $ts);
// print week for the current date
for($i = 1; $i <= 7; $i++) {
// timestamp from ISO week date format
$ts = strtotime($year.'W'.$week.$i);
print date("m/d/Y l", $ts) . "\n";
}
All of which, alongside more information, can be found on this website and credit goes to the author of that post.
I need to find out count of a specific Day between two date.
I can do this by using loop between two date, but if there is difference of 10 years(suppose) between date loop will run 10*365 times.
Is any easier way to do this?
Thanks in advance
function countDays($day, $start, $end)
{
$start = strtotime($start);
$end = strtotime($end);
$datediff = $end - $start;
$days = floor($datediff / (60 * 60 * 24));
//get the day of the week for start and end dates (0-6)
$w = array( date('w', $start ), date('w', $end) );
//get partial week day count
if ($w[0] < $w[1])
{
$partialWeekCount = ($day >= $w[0] && $day <= $w[1]);
}else if ($w[0] == $w[1])
{
$partialWeekCount = $w[0] == $day;
}else
{
$partialWeekCount = ($day >= $w[0]
$day <= $w[1]);
}
//first count the number of complete weeks, then add 1 if $day falls in a partial week.
return intval($days / 7) + $partialWeekCount;
}
Function Call - countDays( 5, "2017-04-14", "2017-04-21")
You are looking for date_diff() function. The date_diff() function returns the difference between two DateTime objects.
<?php
$date1=date_create("2013-03-15");
$date2=date_create("2013-12-12");
$diff=date_diff($date1,$date2);
echo $diff->format("%R%a days");
?>
To find occurrence of specific day (for eg: Sunday). Please note: I have used 7 for Sunday. You can use 1 for Monday, 2 for Tuesday and so on
$cnt = 0;
$start = new DateTime("2013-03-15");
$end = new DateTime("2013-12-12");
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $dt)
{
if ($dt->format('N') == 7)
{
$cnt++;
}
}
echo $cnt;
I am trying to get the start date and end dates of all weeks between two week numbers.
That is one of my date is 2014-05-17 and its week number is 20 and other date is 2014-08-13 and its week number is 33.
My task is to get start and end dates of all weeks between 20 and 33. Here Sunday is the week start and Saturday week end.
$signupweek='2014-05-17';
$signupweek=date("W",strtotime($signupdate));
//week number of current date.
$weekNumber = date("W");
Can anyone help to find the dates.
try this
$signupdate='2014-05-17';
$signupweek=date("W",strtotime($signupdate));
$year=date("Y",strtotime($signupdate));
$currentweek = date("W");
for($i=$signupweek;$i<=$currentweek;$i++) {
$result=getWeek($i,$year);
echo "Week:".$i." Start date:".$result['start']." End date:".$result['end']."<br>";
}
function getWeek($week, $year) {
$dto = new DateTime();
$result['start'] = $dto->setISODate($year, $week, 0)->format('Y-m-d');
$result['end'] = $dto->setISODate($year, $week, 6)->format('Y-m-d');
return $result;
}
Output
Week:20 Start date:2014-05-11 End date:2014-05-17
Week:21 Start date:2014-05-18 End date:2014-05-24
Week:22 Start date:2014-05-25 End date:2014-05-31
Week:23 Start date:2014-06-01 End date:2014-06-07
Week:24 Start date:2014-06-08 End date:2014-06-14
Week:25 Start date:2014-06-15 End date:2014-06-21
Week:26 Start date:2014-06-22 End date:2014-06-28
Week:27 Start date:2014-06-29 End date:2014-07-05
Week:28 Start date:2014-07-06 End date:2014-07-12
Week:29 Start date:2014-07-13 End date:2014-07-19
Week:30 Start date:2014-07-20 End date:2014-07-26
Week:31 Start date:2014-07-27 End date:2014-08-02
Week:32 Start date:2014-08-03 End date:2014-08-09
Week:33 Start date:2014-08-10 End date:2014-08-16
Another method...
If you have a date, from that date you can find the start date and end date of that week. But here week number is not used.
For example:
You have a date 2014-08-13, then required start date is 2014-08-10 and end date is 2014-08-16.
PHP code is
$signupweek='2014-8-13';
/*start day*/
for($i = 0; $i <7 ; $i++)
{
$date = date('Y-m-d', strtotime("-".$i."days", strtotime($signupweek)));
$dayName = date('D', strtotime($date));
if($dayName == "Sun")
{
echo "start day is ". $date."<br>";
}
}
/*end day*/
for($i = 0; $i <7 ; $i++)
{
$date = date('Y-m-d', strtotime("+".$i."days", strtotime($signupweek)));
$dayName = date('D', strtotime($date));
if($dayName == "Sat")
{
echo "end day is ". $date."<br>";
}
}
OUTPUT
start day is 2014-08-10
end day is 2014-08-16
Hope this is useful..
Here's an example that implements the function from this answer:
$signupweek = '2014-05-17';
$signupweek = date("W", strtotime($signupweek));
$current_week = date('W');
$output = array();
// Loop through the weeks BETWEEN your given weeks
// to include the start and end week, remove the +1 below and make
// it $i <= $current_week
for($i = $signupweek + 1; $i < $current_week; $i++) {
// Get the start and end for the current week ($i)
$dates = getStartAndEndDate($i, '2014');
// if the start or end of the week is greater than now, skip it
if(strtotime($dates['start']) > time() or strtotime($dates['end']) > time())
continue;
// Add to output array
$output[] = $dates;
}
function getStartAndEndDate($week, $year)
{
$time = strtotime("1 January $year", time());
$day = date('w', $time);
$time += ((7 * $week) + 1 - $day) * 24 * 3600;
$return['start'] = date('Y-n-j', $time);
$time += 6 * 24 * 3600;
$return['end'] = date('Y-n-j', $time);
return $return;
}
Output
Try this:
$startTime = "2014-05-17";
$startWeek = 20;
$endWeek = 33;
for ($i = 0; $i <= ($endWeek - $startWeek); $i++) {
$days = $i * 7;
echo date("Y-m-d", strtotime($startTime . "+$days day")).'<br />';
}
Unfortunately, it seems that 2014-08-13 is not the start of week 33. 2014-08-16 is.
You can now use DateTime to get start/end dates of week(s)
function getDateRangeForAllWeeks($start, $end){
$fweek = getDateRangeForWeek($start);
$lweek = getDateRangeForWeek($end);
$week_dates = [];
while($fweek['sunday']!=$lweek['sunday']){
$week_dates [] = $fweek;
$date = new DateTime($fweek['sunday']);
$date->modify('next day');
$fweek = getDateRangeForWeek($date->format("Y-m-d"));
}
$week_dates [] = $lweek;
return $week_dates;
}
function getDateRangeForWeek($date){
$dateTime = new DateTime($date);
$monday = clone $dateTime->modify(('Sunday' == $dateTime->format('l')) ? 'Monday last week' : 'Monday this week');
$sunday = clone $dateTime->modify('Sunday this week');
return ['monday'=>$monday->format("Y-m-d"), 'sunday'=>$sunday->format("Y-m-d")];
}
print_r( getDateRangeForWeek("2016-05-07") );
print_r( getDateRangeForAllWeeks("2015-11-07", "2016-02-15") );
Let's assume I have two dates in variables, like
$date1 = "2009-09-01";
$date2 = "2010-05-01";
I need to get the count of months between $date2 and $date1($date2 >= $date1). I.e. i need to get 8.
Is there a way to get it by using date function, or I have to explode my strings and do required calculations?
Thanks.
For PHP >= 5.3
$d1 = new DateTime("2009-09-01");
$d2 = new DateTime("2010-05-01");
var_dump($d1->diff($d2)->m); // int(4)
var_dump($d1->diff($d2)->m + ($d1->diff($d2)->y*12)); // int(8)
DateTime::diff returns a DateInterval object
If you don't run with PHP 5.3 or higher, I guess you'll have to use unix timestamps :
$d1 = "2009-09-01";
$d2 = "2010-05-01";
echo (int)abs((strtotime($d1) - strtotime($d2))/(60*60*24*30)); // 8
But it's not very precise (there isn't always 30 days per month).
Last thing : if those dates come from your database, then use your DBMS to do this job, not PHP.
Edit: This code should be more precise if you can't use DateTime::diff or your RDBMS :
$d1 = strtotime("2009-09-01");
$d2 = strtotime("2010-05-01");
$min_date = min($d1, $d2);
$max_date = max($d1, $d2);
$i = 0;
while (($min_date = strtotime("+1 MONTH", $min_date)) <= $max_date) {
$i++;
}
echo $i; // 8
Or, if you want the procedural style:
$date1 = new DateTime("2009-09-01");
$date2 = new DateTime("2010-05-01");
$interval = date_diff($date1, $date2);
echo $interval->m + ($interval->y * 12) . ' months';
UPDATE: Added the bit of code to account for the years.
Or a simple calculation would give :
$numberOfMonths = abs((date('Y', $endDate) - date('Y', $startDate))*12 + (date('m', $endDate) - date('m', $startDate)))+1;
Accurate and works in all cases.
This is another way to get the number of months between two dates:
// Set dates
$dateIni = '2014-07-01';
$dateFin = '2016-07-01';
// Get year and month of initial date (From)
$yearIni = date("Y", strtotime($dateIni));
$monthIni = date("m", strtotime($dateIni));
// Get year an month of finish date (To)
$yearFin = date("Y", strtotime($dateFin));
$monthFin = date("m", strtotime($dateFin));
// Checking if both dates are some year
if ($yearIni == $yearFin) {
$numberOfMonths = ($monthFin-$monthIni) + 1;
} else {
$numberOfMonths = ((($yearFin - $yearIni) * 12) - $monthIni) + 1 + $monthFin;
}
I use this:
$d1 = new DateTime("2009-09-01");
$d2 = new DateTime("2010-09-01");
$months = 0;
$d1->add(new \DateInterval('P1M'));
while ($d1 <= $d2){
$months ++;
$d1->add(new \DateInterval('P1M'));
}
print_r($months);
Using DateTime, this will give you a more accurate solution for any amount of months:
$d1 = new DateTime("2011-05-14");
$d2 = new DateTime();
$d3 = $d1->diff($d2);
$d4 = ($d3->y*12)+$d3->m;
echo $d4;
You would still need to handle the leftover days $d3->d if your real world problem is not as simple and cut and dry as the original question where both dates are on the first of the month.
This is a simple method I wrote in my class to count the number of months involved into two given dates :
public function nb_mois($date1, $date2)
{
$begin = new DateTime( $date1 );
$end = new DateTime( $date2 );
$end = $end->modify( '+1 month' );
$interval = DateInterval::createFromDateString('1 month');
$period = new DatePeriod($begin, $interval, $end);
$counter = 0;
foreach($period as $dt) {
$counter++;
}
return $counter;
}
In case the dates are part of a resultset from a mySQL query, it is much easier to use the TIMESTAMPDIFF function for your date calculations and you can specify return units eg. Select TIMESTAMPDIFF(MONTH, start_date, end_date)months_diff from table_name
strtotime is not very precise, it makes an approximate count, it does not take into account the actual days of the month.
it's better to bring the dates to a day that is always present in every month.
$date1 = "2009-09-01";
$date2 = "2010-05-01";
$d1 = mktime(0, 0, 1, date('m', strtotime($date1)), 1, date('Y', strtotime($date1)));
$d2 = mktime(0, 0, 1, date('m', strtotime($date2)), 1, date('Y', strtotime($date2)));
$total_month = 0;
while (($d1 = strtotime("+1 MONTH", $d1)) <= $d2) {
$total_month++;
}
echo $total_month;
I have used this and works in all conditions
$fiscal_year = mysql_fetch_row(mysql_query("SELECT begin,end,closed FROM fiscal_year WHERE id = '2'"));
$date1 = $fiscal_year['begin'];
$date2 = $fiscal_year['end'];
$ts1 = strtotime($date1);
$ts2 = strtotime($date2);
$te=date('m',$ts2-$ts1);
echo $te;
I am trying to create an array starting with today and going back the last 30 days with PHP and I am having trouble. I can estimate but I don’t know a good way of doing it and taking into account the number of days in the previous month etc. Does anyone have a good solution? I can’t get close but I need to make sure it is 100% accurate.
Try this:
<?php
$d = array();
for($i = 0; $i < 30; $i++)
$d[] = date("d", strtotime('-'. $i .' days'));
?>
Here is advance latest snippet for the same,
$today = new DateTime(); // today
$begin = $today->sub(new DateInterval('P30D')); //created 30 days interval back
$end = new DateTime();
$end = $end->modify('+1 day'); // interval generates upto last day
$interval = new DateInterval('P1D'); // 1d interval range
$daterange = new DatePeriod($begin, $interval, $end); // it always runs forwards in date
foreach ($daterange as $date) { // date object
$d[] = $date->format("Y-m-d"); // your date
}
print_r($d);
Working demo.
Official doc.
For those who want to show sales of the past X days,
As asked in this closed question (https://stackoverflow.com/questions/11193191/how-to-get-last-7-days-using-php#=), this worked for me.
$sales = Sale::find_all();//the sales object or array
for($i=0; $i<7; $i++){
$sale_sum = 0; //sum of sale initial
if($i==0){
$day = strtotime("today");
} else {
$day = strtotime("$i days ago");
}
$thisDayInWords = strftime("%A", $day);
foreach($sales as $sale){
$date = strtotime($sale->date_of_sale)); //May 30th 2018 10:00:00 AM
$dateInWords = strftime("%A", $date);
if($dateInWords == $thisDayInWords){
$sale_sum += $sale->total_sale;//add only sales of this date... or whatever
}
}
//display the results of each day's sale
echo $thisDayInWords."-".$sale_sum; ?>
}
Before you get angry:
I placed this answer here to help someone who was directed here from that question. Couldn't answer there :(
You can use time to control the days:
for ($i = 0; $i < 30; $i++)
{
$timestamp = time();
$tm = 86400 * $i; // 60 * 60 * 24 = 86400 = 1 day in seconds
$tm = $timestamp - $tm;
$the_date = date("m/d/Y", $tm);
}
Now, within the for loop you can use the $the_date variable for whatever purposes you might want to. :-)
$d = array();
for($i = 0; $i < 30; $i++)
array_unshift($d,strtotime('-'. $i .' days'));