Get day names between two date in PHP - php

How to get name of days between two dates in PHP?
Input:
Start Date: 01-01-2013
End date: 05-01-2013
Output:
Tuesday
Wednesday
Thursday
Friday
Saturday
Tried code
$from_date ='01-01-2013';
$to_date ='05-01-2013';
$number_of_days = count_days(strtotime($from_date),strtotime($to_date));
for($i = 1; $i<=$number_of_days; $i++)
{
$day = Date('l',mktime(0,0,0,date('m'),date('d')+$i,date('y')));
echo "<br>".$day;
}
function count_days( $a, $b )
{
$gd_a = getdate( $a );
$gd_b = getdate( $b );
$a_new = mktime( 12, 0, 0, $gd_a['mon'], $gd_a['mday'], $gd_a['year'] );
$b_new = mktime( 12, 0, 0, $gd_b['mon'], $gd_b['mday'], $gd_b['year'] );
return round( abs( $a_new - $b_new ) / 86400 );
}
I saw the post Finding date of particular day between two dates PHP
But I don't got my result
Please help me

Use the DateTime class, it will be much more simple:
$from_date ='01-01-2013';
$to_date ='05-01-2013';
$from_date = new DateTime($from_date);
$to_date = new DateTime($to_date);
for ($date = $from_date; $date <= $to_date; $date->modify('+1 day')) {
echo $date->format('l') . "\n";
}

$from_date ='01-01-2013';
$to_date ='05-01-2013';
$start = strtotime($from_date);
$end = strtotime($to_date);
$day = (24*60*60);
for($i=$start; $i<= $end; $i+=86400)
echo date('l', $i);

<?php
function printDays($from, $to) {
$from_date=strtotime($from);
$to_date=strtotime($to);
$current=$from_date;
while($current<=$to_date) {
$days[]=date('l', $current);
$current=$current+86400;
}
foreach($days as $key=> $day) {
echo $day."\n";
}
}
$from_date ='01-01-2013';
$to_date ='05-01-2013';
printDays($from_date, $to_date);
?>
Loop through every day between the given dates (inclusive) and then add the corresponding day in an array, using date function. Print out the array and tada! you're done!

Related

Get whole week date starting from sunday to saturday from given date

Hello guys i am working in php and my requirement is to get complete week dates from given date as i need to calculate weekly working hour. And week must be started from sunday to saturday not monday to sunday. I have code which works properly for other days of week except sunday. it means if give any dates from monday to saturday it works properly but if i give sunday's date it give last week's dates. please check my code and advise me for better solution.
$days = array();
$ddate = "2018-01-07";
$date = new DateTime($ddate);
$week = $date->format("W");
$y = date("Y", strtotime($ddate));
echo "Weeknummer: $week"."<br>";
echo "Year: $y"."<br>";
for($day=0; $day<=6; $day++)
{
$days[$day] = date('Y-m-d', strtotime($y."W".$week.$day))."<br>";
}
print_r($days);
Using the DateTime, DateInterval and DatePeriod classes you could do it like this perhaps
function getperiod( $start ){
return new DatePeriod(
new DateTime( $start ),
new DateInterval('P1D'),
new DateTime( date( DATE_COOKIE, strtotime( $start . '+ 7days' ) ) )
);
}
$start='2018-01-07';
$period=getperiod( $start );
foreach( $period as $date ){
echo $date->format('l -> Y-m-d') . '<br />';
}
Which returns
Sunday -> 2018-01-07
Monday -> 2018-01-08
Tuesday -> 2018-01-09
Wednesday -> 2018-01-10
Thursday -> 2018-01-11
Friday -> 2018-01-12
Saturday -> 2018-01-13
Or, by modifying the parameters of the getperiod function you can make that function far more flexible.
function getperiod( $start, $interval='P1D', $days=7 ){
return new DatePeriod(
new DateTime( $start ),
new DateInterval( $interval ),
new DateTime( date( DATE_COOKIE, strtotime( $start . '+ '.$days.' days' ) ) )
);
}
$start='2018-01-07';
$days=array();
$period=getperiod( $start );
foreach( $period as $date ){
$days[]=$date->format('Y-m-d');
}
echo '<pre>',print_r($days,true),'</pre>';
For instance: To find every Sunday for the next year
$period=getperiod( $start,'P7D', 365 );
foreach( $period as $date ){
$days[]=$date->format('Y-m-d');
}
echo '<pre>',print_r($days,true),'</pre>';
To ensure that the calculations begin on a Sunday which has a numeric value of 7
function getperiod( $start, $interval='P1D', $days=7 ){
return new DatePeriod(
new DateTime( $start ),
new DateInterval( $interval ),
new DateTime( date( DATE_COOKIE, strtotime( $start . '+ '.$days.' days' ) ) )
);
}
/* A date from which to begin calculations */
$start='2018-01-01';
/* Array to store output */
$days=array();
/* integer to represent which day of the week to operate upon */
$startday = 7;
/* Output format for resultant dates */
$output='Y-m-d';
/* Calculate initial startdate given above variables */
$start=date( DATE_COOKIE, strtotime( $start . ' + ' . ( $startday - date( 'N', strtotime( $start ) ) ) . ' days' ) );
/* Get the period range */
$period=getperiod( $start );
foreach( $period as $date ){
/* store output in desired format */
$days[]=$date->format( $output );
}
/* do something with data */
echo '<pre>',print_r($days,true),'</pre>';
From source,
Here is the snippet you are looking for,
// set current date
$date = '01/03/2018';
// 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";
}
Here is working demo.
If you need normal standard format code,
Here is your snippet,
// set current date
$date = '2018-01-03';
// 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("Y-m-d l", $ts) . "\n";
}
Here is working demo.
EDIT
As per your requirement, now week will start from sunday to saturday
<?php
// set current date
$date = '2018-01-03';
// parse about any English textual datetime description into a Unix timestamp
$ts = strtotime($date);
// calculate the number of days since Sunday
$dow = date('w', $ts);
$offset = $dow;
if ($offset < 0) {
$offset = 6;
}
// calculate timestamp for the Sunday
$ts = $ts - $offset * 86400;
// loop from Sunday till Saturday
for ($i = 0; $i < 7; $i++, $ts += 86400) {
print date("Y-m-d l", $ts) . "\n";
}
<?php
$days = array();
$ddate = "2018-01-07";
$y = date("Y", strtotime($ddate));
if(date("l", strtotime($ddate))=='Sunday'){
$ddate = date("Y-m-d ", strtotime($ddate. "+1 day"));
}
$date = new DateTime($ddate);
$week = $date->format("W");
echo "<br/>";
echo "Weeknummer: $week"."<br>";
echo "Year: $y"."<br>";
for($day=0; $day<=6; $day++)
{
$days[$day] = date('Y-m-d', strtotime($y."W".$week.$day))."<br>";
}
print_r($days);
?>
try this:
$days = array();
$ddate = "2018-01-07";
$date = new DateTime($ddate);
$week = $date->format("N")==7?$date->modify("+1 week")->format("W"):$date->format("W");
$y = date("Y", strtotime($ddate));
echo "Weeknummer: $week"."<br>";
echo "Year: $y"."<br>";
for($day=0; $day<=6; $day++)
{
$days[$day] = date('Y-m-d', strtotime($y."W".$week.$day))."<br>";
}
print_r($days);
$dto = new DateTime();
$year = date_create($this->week_date)->format('o');
$week_no = date('W', strtotime($this->week_date));
$dto->setISODate($year, $week_no);
$dto->modify('-1 days');
$ret['sunday'] = $dto->format('Y-m-d');
$dto->modify('+1 days');
$ret['monday'] = $dto->format('Y-m-d');
$dto->modify('+1 days');
$ret['tuesday'] = $dto->format('Y-m-d');
$dto->modify('+1 days');
$ret['wednesday'] = $dto->format('Y-m-d');
$dto->modify('+1 days');
$ret['thursday'] = $dto->format('Y-m-d');
$dto->modify('+1 days');
$ret['friday'] = $dto->format('Y-m-d');
$dto->modify('+1 days');
$ret['saturday'] = $dto->format('Y-m-d');
$dto->modify('+1 days');
$ret['next_sunday'] = $dto->format('Y-m-d');

Transform PHP script to a general-case function

I have this code that modify date in the way I want, for example, if starting date is 31/01/2000, adding 1 month will return 29/02/2000, then, 31/03/2000.
If date is 30/01/2000 (not last day of the month) it will return 29/02/2000, then 30/03/2000, 30/04/2000 and so on.
I want to transfirm that code in a general case function, to be able to add 1,3,6,12 months, and inside the for loop, to work all corect.
I would like it to be a function 2 or 3 arguments, startingDate, duration(nr of iterations), frequency (add 1/3/6/12 months per once).
<?php
$date = new DateTime('2000-01-28'); // or whatever
#echo $date->format('d')." ".$date->format('t');
$expectedDay = $date->format('d');
$month = $date->format('m');
$year = $date->format('Y');
for ($i = 0; $i < 100; $i++) {
echo $date->format('Y-m-d') . "<br>";
if ($month++ == 12) {
$year++;
$month = 1;
}
$date->modify("${year}-${month}-1");
if ($expectedDay > $date->format('t')) {
$day = $date->format('t');
} else {
$day = $expectedDay;
}
$date->modify("${year}-${month}-${day}");
}
Whelp, there's an extremely easy function for this in PHP nowadays.
first, you get a timestamp instead of a datetime:
$timestamp = $date->getTimestamp();
Now, just use strtotime to add onto the date.
strtotime("+1 month", $myTimestamp);
You can change the +1 into anything you want, so you just throw the amount in the string and voila; a dynamic way of adding them!
however, since you want to do +30 days instead of a natural month, you're better off just adding 30 days to the timestamp, like so:
$timestamp = $timestamp + (3600 * 24 * 30); //s per h * h per d * d
So, you'd end up with something like this:
function calculateTime($startingDate, $iterations, $frequency){
$timeStamp = strtotime($startingDate);//if you expect a string date
$timeToAdd = (3600 * 24 * 30) * $frequency; //30 days * frequency
$return = array();
$return[] = date('Y-m-d', $timeStamp); //Original date
$previousDate = $timeStamp; //Original date for now
for($i = 0; $i < $iterations; $i++){
$newDate = $previousDate + (3600 * 24 * 30);
$return[] = date('Y-m-d', $newDate);
$previousDate = $newDate;
}
return $return;
}
And then for the rendering part:
//Let's render this stuff
$dates = calculateTime('24-08-2017', 25, 3);
foreach($dates as $date){
echo "$date</br>";
}
If you'd like to do it with full months, something like this:
<?php
function calculateTime($startingDate, $iterations, $frequency){
$timeStamp = strtotime($startingDate);//if you expect a string date
$return = array();
$return[] = date('Y-m-d', $timeStamp); //Original date
$previousDate = $timeStamp; //Original date for now
for($i = 0; $i < $iterations; $i++){
$lastDay = false;
//It's the last day of the month
if(date('t', $timeStamp) == date('d', $timeStamp)){
$lastDay = true;
}
if($frequency == 12){
$newDate = strtotime('+1 year', $previousDate);
}
else{
if($lastDay){
$firstDayOfMonth = strtotime(date("01-m-Y", $previousDate));
$newDate =strtotime("+$frequency month", $firstDayOfMonth);
}
else{
$newDate = strtotime("+$frequency month", $previousDate);
}
}
if($lastDay){
$return[] = date('Y-m-t', $newDate);
}
else{
$return[] = date('Y-m-d', $newDate);
}
$previousDate = $newDate;
}
return $return;
}
//Let's render this stuff
$dates = calculateTime('31-01-2000', 25, 1);
foreach($dates as $date){
echo "$date</br>";
}
I hope this helps? :)
If you'd like to see how this works quickly, just paste my code into a phpfiddle. Unfortunately the save function is broken right now.

Calculate days in months between two dates with PHP

I have a period with startdate of 2016-12-26 and end date 2017-03-04.
Now I would like to find out how many days in each months there is, from a given period. Expected output from the above period dates (array):
2016-12: 5
2017-01: 31
2017-02: 28
2017-03: 4
How can I accomplish this cleanest way? I have tried to:
first looking at the period_start, get the days = 26 and
find out the start/end dates of the months between 2016-12 and 2017-03, to then calculate the days here (31 respectively 28 in february)
then finally calculating the 4 days in 2017-03.
But is there any cleaner/better way?
This can be achieved easily using the DateTime class. Create the objects, and use DateTime::diff() on them, then use the days property.
$start = new DateTime("2016-12-26");
$end = new DateTime("2017-03-04");
echo $start->diff($end)->days; // Output: 68
Live demo
http://php.net/datetime.construct
#Karem hope this logic will help you, this is working case for all your conditions please try this below one:
<?php
$startDate = '2016-12-26';
$endDate = '2017-03-04';
$varDate = $startDate;
while($varDate < $endDate){
$d = date('d', strtotime($varDate));
$Y = date('Y', strtotime($varDate));
$m = date('m', strtotime($varDate));
$days = cal_days_in_month(CAL_GREGORIAN,$m,$Y);
$time = strtotime($varDate);
if($varDate == $startDate){
$time = strtotime(date('Y-m-01', $time));
$days = $days - $d;
}
else if(date("Y-m", strtotime($varDate)) == date("Y-m", strtotime($endDate))){
$days = date("j", strtotime($endDate));
}
echo date('Y-m', strtotime($varDate)). ": ".$days."<br>";
$varDate = date('Y-m-d', strtotime("+1 month", $time));
}
This is long but easy to understand that how to achieve you your goal
<?php
function getMonthDays($start,$end){
if($start < $end){
$start_time = strtotime($start);
$last_day_of_start = strtotime(date("Y-m-t",$start_time));
$start_month_days = ($last_day_of_start - $start_time)/(60*60*24);
echo date("Y-m",$start_time).": ".$start_month_days."\n";
$days = "";
$start = date("Y-m-d", strtotime("+1 month", $start_time));
$start_time = strtotime($start);
while($start < $end){
$month = date("m",$start_time);
$year = date("Y",$start_time);
$days = date('t', mktime(0, 0, 0, $month, 1, $year));
echo date("Y-m",$start_time).": ".$days."\n";
$start = date("Y-m-d", strtotime("+1 month", $start_time));
$start_time = strtotime($start);
}
echo date("Y-m",strtotime($end)).": ".date("d",strtotime($end))."\n";
}else{
echo "Wrong Input";
}
}
getMonthDays('2016-12-26','2017-03-04');
?>
live demo : https://eval.in/781724
Function returns array : https://eval.in/781741
<?php
$d1 = strtotime('2016-12-26');
$d2 = strtotime('2017-03-04');
echo floor(($d2 - $d1)/(60*60*24));
?>
i used Carbon (https://carbon.nesbot.com/docs/) but you can do it with any other time lib.
$startDate = Carbon::createFromFormat('!Y-m-d', '2017-01-11');;
$endDate = Carbon::createFromFormat('!Y-m-d', '2018-11-13');;
$diffInMonths = $endDate->diffInMonths($startDate);
for ($i = 0; $i <= $diffInMonths; $i++) {
$start = $i == 0 ? $startDate->copy()->addMonth($i) : $startDate->copy()->addMonth($i)->firstOfMonth();
$end = $diffInMonths == $i ? $endDate->copy() : $start->copy()->endOfMonth();
echo $end->format('Y-m') . ' ' . ($end->diffInDays($start) + 1) . PHP_EOL;
}

Get month name using start date and end date?

$startDate = "2014-03-01";
$endDate= "2014-05-25";
Result required: March, April, May;
for that PHP delivers the DatePeriod object. Just have a look at the following example.
$period = new DatePeriod(
new DateTime('2014-03-01'),
DateInterval::createFromDateString('1 month'),
new DateTime('2014-05-25')
);
foreach ($period as $month) {
echo strftime('%B', $month->format('U'));
}
A quick solution is to parse each day and check it month:
$startDate = "2014-03-01";
$endDate = "2014-05-25";
$start = strtotime($startDate);
$end = strtotime($endDate);
$result = array();
while ( $start <= $end )
{
$month = date("M", $start);
if( !in_array($month, $result) )
$result[] = $month;
$start += 86400;
}
print_r($result);
I believe it can be done much efficient by new OOP (DateTime object) approach, but this is fast and no-brain if you need to make it work.
<?php
$startDate = "2014-03-01";
echo date('F',strtotime($startDate));
?
$date = date('F',strtotime($startDate));
For full month representation (ie Januaray, February, etc)
$date = date('M',strtotime($startDate));
For abbreviated...(ie Jan, Feb, Mar)
REFERENCE
If you wanna echo out those months in between based on two dates....
$d = "2014-03-01";
$startDate = new DateTime($d);
$endDate = new DateTime("2014-05-01");
function diffInMonths(DateTime $date1, DateTime $date2)
{
$diff = $date1->diff($date2);
$months = $diff->y * 12 + $diff->m + $diff->d / 30;
return (int) round($months);
}
$t = diffInMonths($startDate, $endDate);
for($i=0;$i<$t+1;$i++){
echo date('F',strtotime($d. '+'.$i.' Months'));
}
PHP SANDBOX EXAMPLE

Get mondays tuesdays etc

How can I echo all dates for mondays/ wednesday / friday between these two dates?
This is what I have been working with:
function get_days ( $s, $e )
{
$r = array ();
$s = strtotime ( $s . ' GMT' );
$e = strtotime ( $e . ' GMT' );
$day = gmdate ( 'l', $s );
do
{
$r[] = $day . ', ' . gmdate ( 'Y-m-d', $s );
$s += 86400 * 7;
} while ( $s <= $e );
return $r;
}
print_r ( get_days ( $start, $end ) );
Try this:
function getDates($start_date, $end_date, $days){
// parse the $start_date and $end_date string values
$stime=new DateTime($start_date);
$etime=new DateTime($end_date);
// make a copy so we can increment by day
$ctime = clone $stime;
$results = array();
while( $ctime <= $etime ){
$dow=$ctime->format("w");
// assumes $days is array containing integers for Sun (0) - Sat (6)
if( in_array($dow, $days) ){
// make a copy to return in results
$results[]=clone $ctime;
}
// incrememnt by 1 day
//$ctime=date_add($ctime, date_interval_create_from_date_string('1 days'));
$ctime->modify("+1 days");
}
return $results;
}
// get every Tues, Wed, Fri from now to End of June
getDates('2011-06-15','2011-06-30',array(2,3,5));
You should be able to get the days using strtotime(). It accepts arguments like next Tuesday and also parses 2011-06-15 into a correct timestamp. And yes, you need one (or more) loop(s).
This should be sufficient to point you in the right direction.
Ok, you updated your question while I was writing my answer. You can't assume that a day always has 86400 seconds. When DST starts or ends your assumption will be incorrect.
<?php
$start = "1 Jan 2011";
$end = "20 Jan 2011";
$dates = getDays($start, $end);
print_r($dates);
function getDays($start,$end)
{
$t = new DateTime("$start 12:00");
$e = new DateTime($end ." 12:00");
$out = array();
for (; $t<=$e; $t->modify("+1 day")) {
$day = $t->format("D");
if (in_array($day, array('Mon','Wed','Fri'))) {
$out[] = $t->format('d M Y');
}
}
return $out;
}

Categories