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

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"));

Related

How to get the name of the day in PHP using date?

Is it possible to get the name of the day in the row of numbers converted to date?
I have Code :
$date1 = date('Y-m-01');
$Month = date('m', strtotime($date1));
$Year = date('Y', strtotime($date1));
$Maximum_Date = date('t', strtotime($date1));
for($Date = 1; $Date <= $Maximum_Date; $Date++){
$DataDate = $Date . ' ' . $Month . ' ' . $Year . '<BR>';
echo $DataDate;
}
Result :
1 04 2019
2 04 2019
3 04 2019
etc..
What I want is to change it to display the name of the day on that date
For Example Date in April :
Monday, 1 04 2019
Tuesday, 2 04 2019
Wednesday, 3 04 2019
etc..
[UPDATE] April 15, 2019
Refer to comments, I see documentation here and apply with mktime();
So I Update The Code :
$date1 = date('Y-m-01');
$Month = date('m', strtotime($date1));
$Year = date('Y', strtotime($date1));
$Maximum_Date = date('t', strtotime($date1));
for($Date = 1; $Date <= $Maximum_Date; $Date++){
echo date("l, d m Y", mktime(0, 0, 0, $Month, $Date, $Year)) . '<br>';
}
And get the result :
Monday, 1 04 2019
Tuesday, 2 04 2019
Wednesday, 3 04 2019
etc..
You can simplify this a lot without converting back and forth between date and strtotime:
$year = date('Y');
$month = date('n');
$lastDay = date('t');
foreach (range(1, $lastDay) as $day) {
echo date('D, j m Y', mktime(0, 0, 0, $month, $day, $year)), '<br>';
}
See http://php.net/mktime.
Omitting implicit default values and condensing it a bit, you can in fact boil it down to:
foreach (range(1, date('t')) as $day) {
echo date('D, j m Y', mktime(0, 0, 0, date('n'), $day)), '<br>';
}
Mon, 1 04 2019
Tue, 2 04 2019
Wed, 3 04 2019
...
Tue, 30 04 2019
Note that this code has a minuscule potential to break, should you execute it right at the second in which one month rolls over to the next, and the date('n') and date('t') functions happen to be called "in different months". To avoid that possibility entirely, make this operation atomic:
list($year, $month, $lastDay) = explode(' ', date('Y n t'));
foreach (range(1, $lastDay) as $day) {
echo date('D, j m Y', mktime(0, 0, 0, $month, $day, $year)), '<br>';
}
The code below will print out what you need..
$date1 = date('Y-m-01');
$Maximum_Date = date('t', strtotime($date1));
for($Date = 1; $Date <= $Maximum_Date; $Date++)
{
$thatDay = date('Y-m-'.$Date);
$day = date('l, j', strtotime($thatDay));
$Month = date('m', strtotime($thatDay));
$Year = date('Y', strtotime($thatDay));
echo $day . ' ' . $Month . ' ' . $Year . '<BR>';
}
Output:
Monday, 1 04 2019
Tuesday, 2 04 2019
Wednesday, 3 04 2019
Thursday, 4 04 2019
Friday, 5 04 2019
...
...
if you change this line
$day = date('l, j', strtotime($thatDay));
TO
$day = date('l, jS', strtotime($thatDay));
The output will be: Monday, 1st 04 2019
Use:
$date1 = date('Y-m-01');
$Month = date('m', strtotime($date1));
$Year = date('Y', strtotime($date1));
$Maximum_Date = date('t', strtotime($date1));
for($Date = 1; $Date <= $Maximum_Date; $Date++){
$DataDate = date("D-m-Y",strtotime($Year."-".$Month."-".$Date));
echo $DataDate. '<br>';;
}
You should try like below.
$date1 = date('Y-m-01');
$Month = date('m', strtotime($date1));
$Year = date('Y', strtotime($date1));
$Maximum_Date = date('t', strtotime($date1));
$StartDate=$date1;
$EndDate=($Year."-".$Month."-".$Maximum_Date);
$EndDate=date('Y-m-d',strtotime($EndDate));
while(strtotime($EndDate)>=strtotime($StartDate))
{
echo date('l, d-m-Y',strtotime($StartDate))."<br/>";
$StartDate=date('Y-m-d', strtotime($StartDate . ' +1 day'));
}
After execute you will get result like below.
Monday, 01-04-2019
Tuesday, 02-04-2019
Wednesday, 03-04-2019
...................
...................
...................
...................
Saturday, 27-04-2019
Sunday, 28-04-2019
Monday, 29-04-2019
Tuesday, 30-04-2019
Add the following line to your loop:
echo (new DateTime($Date. '-'. $Month .'-'. $Year))->format('l');
It creates a new DateTime object with your data & echo's the day in the format that you requested.

Get first day of current week - x

I need to get the first day of the week (Monday), 8 weeks back from today, where 8 is a variable.
What's the best way to do that in PHP?
You can do this way
echo date("l M-d-Y", strtotime('monday this week'));
echo date("l M-d-Y", strtotime('sunday this week'));
echo date("l M-d-Y", strtotime('monday last week'));
echo date("l M-d-Y", strtotime('sunday last week'));
echo date("l M-d-Y", strtotime('monday next week'));
echo date("l M-d-Y", strtotime('sunday next week'));
You can also search monthwise
echo date("l M-d-Y", strtotime('first day of this month'));
echo date("l M-d-Y", strtotime('last day of this month'));
echo date("l M-d-Y", strtotime('first day of last month'));
echo date("l M-d-Y", strtotime('last day of last month'));
echo date("l M-d-Y", strtotime('first day of next month'));
echo date("l M-d-Y", strtotime('last day of next month'));
$weeks = 8;
// Timestamp for $weeks weeks ago
$time = strtotime("$weeks weeks ago");
// Day of the week for $time (1 - Mon, ...)
$week_day = date('N', $time);
// Number of days from Monday
$diff = $week_day - 1;
// The date of the Monday $weeks weeks ago
echo date('j', $time - ($diff * 24 * 3600));
It's not really complicated actually, all you got to do is play a little bit with datetimes ;
<?php
$dt = new Datetime(sprintf('%d weeks ago', 8)); // replace 8 with variable, your value, whatever
$day = $dt->format('w');
$dt->modify(sprintf('%d days go', ($day - 1) % 7));
your $dt should then have the value you seek
You can make some math with dates in PHP like:
$now = date('F d, Y H:i');
$newdate = date('F d, Y H:i', strtotime($now.' - 8 weeks'));
echo $newdate;
In this case it will output a current date minus 8 weeks.
Also to count which day is today you can use:
$dw = date( "w", strtotime($newdate));
Where $dw will be 0 (for Sunday) through 6 (for Saturday) more informations can be found: PHP: date
Solution
In your case it would look as follows:
<?php
$weeks = 8;
$now = date('F d, Y H:i:s');
$newdate = date('F d, Y H:i:s', strtotime($now.' - '.$weeks.' weeks'));
$new_date_day = date( "w", strtotime($newdate));
$minus = $new_date_day - 1;
if ($minus < 0) { //check if sunday
$plus = $minus * -1;
$newdate = date('F d, Y H:i:s', strtotime($newdate.' + '.$plus.' days'));
} else {
$newdate = date('F d, Y H:i:s', strtotime($newdate.' - '.$minus.' days'));
}
echo $newdate;
?>
Of course you can echo what ever style of date you want. F.ex. F d, Y H:i:s will output November 28, 2016 06:18:03.

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

Change today, yesterday and this week's dates to relative, human-readable format

I'm pulling in some tweets and I'd love to output whether or not they came in today, yesterday, or before that. Here's the code that I'm working with (which doesn't work). It's skipping the if and else if and going straight to the else.
date_default_timezone_set("America/New_York");
$time = $block["created_at"];
$time = strtotime($time);
if(date("now") == date("m-d-Y", $time)) {
$time = date("g:ia", $time);
}
else if(date(strtotime("-1 day")) == date("m-d-Y", $time)) {
$time = "Yesterday at" + date("g:ia", $time);
}
else {
$time = date("m-d-Y g:ia", $time);
}
Absolutely ideally, I'd also love it if, when the timestamp falls within the last 6 days, it shows the day of the week and the time, and anything older than that will show the date.
So the stream might look like this (dates sorted descending):
[...] 9:53am
[...] 7:02am
[...] Yesterday at 11:24pm
[...] Monday at 3:45pm
[...] Jan 2, 2013
Any idea as to where my code is going awry? Thanks!
Your code should look liike below.
if(date("m-d-Y") == date("m-d-Y", $time)) {
$time = date("g:ia", $time);
}
else if(date("m-d-Y", strtotime("-1 day")) == date("m-d-Y", $time)) {
$time = "Yesterday at" + date("g:ia", $time);
}
else {
$time = date("m-d-Y g:ia", $time);
}
Explanation
date() — Format a local time/date. Returns a string formatted according to the given format string using the given integer timestamp or the current time if no timestamp is given. In other words, timestamp is optional and defaults to the value of time().
Where have you gone wrong ?
You should 1st pass the format then the timestamp to the date() function. Read more.
The strtotime function can parse various strings:
echo date("D Y-m-d H:i:s"); // Wed 2013-01-09 21:33:07
echo date("D Y-m-d H:i:s", strtotime("today 00:00" )); // Wed 2013-01-09 00:00:00
echo date("D Y-m-d H:i:s", strtotime("yesterday 00:00")); // Tue 2013-01-08 00:00:00
echo date("D Y-m-d H:i:s", strtotime("-6 day 00:00" )); // Thu 2013-01-03 00:00:00
echo date("D Y-m-d H:i:s", strtotime("-100 day 00:00" )); // Mon 2012-10-01 00:00:00
All you need to do now is to compare the given timestamp with the above in descending order:
function formatDate($time) {
if ($time >= strtotime("today 00:00")) {
return date("g:i A", $time);
} elseif ($time >= strtotime("yesterday 00:00")) {
return "Yesterday at " . date("g:i A", $time);
} elseif ($time >= strtotime("-6 day 00:00")) {
return date("l \\a\\t g:i A", $time);
} else {
return date("M j, Y", $time);
}
}
echo formatDate(time()); // 9:42 PM
echo formatDate(strtotime("-1 day")); // Yesterday at 9:42 PM
echo formatDate(strtotime("-6 day")); // Thursday at 9:42 PM
echo formatDate(strtotime("-100 day")); // Oct 10, 2012
Note that strtotime() returns a timestamp (an integer) while date() returns a string. The function compares timestamps with timestamp.

how to get the previous 3 months in php

how to get the previous 3 months in php ex(If i say DEC.. It should display the previous 3 months i.e., OCT NOV DEC)
You can use the strtotime function like this:
echo date('M', strtotime('-3 month'));
So you specify previous dates with minus sign.
echo date('M', strtotime('0 month'));
echo date('M', strtotime('-1 month'));
echo date('M', strtotime('-2 month'));
echo date('M', strtotime('-3 month'));
Results:
Dec
Nov
Oct
Sep
You can do the same if you are using a loop like this:
for ($i = -3; $i <= 0; $i++){
echo date('M', strtotime("$i month"));
}
Results:
Sep
Oct
Nov
Dec
Check out the documentation too see many other friendly date and time keywords strtotime supports:
http://php.net/manual/en/function.strtotime.php
Voted answer is almost correct.
Correct solution is:
for ($i = -3; $i <= 0; $i++){
echo date('M', strtotime("$i month", strtotime(date("Y-m-15"))));
}
Explain: strtotime default implementation is:
date ( string $format [, int $timestamp = time() ] ) : string
As you can see there is timestamp with default value of: time().
Last say today is 31th March.
Because there is no 31th Feb
echo date('M', strtotime("-1 month"));
will return March
On the other hand:
echo date('M', strtotime("+1 month"));
will return May (April will be skipped).
Because of that issue we have to setup timestamp value which is a safe date.
Every date between 1-28 is safe because every month have got that date. In my example I had choose 15th day of month.
$month = date('M');
$year = date('Y');
$no_of_mnths = date('n',strtotime("-2 months"));
$remaining_months = (12 - $no_of_mnths)."\r\n";
$tot = $remaining_months+1;
for($j=0;$j<$tot;$j++){
echo date('M',strtotime(''.$no_of_mnths.' months'))
$no_of_mnths++;
}
This may help you`
<?php
$date = explode("-", "2016-08-31");
if($date[2]== "01"){$days = "-0 days";}else{$days = "-1 days";}
$time = strtotime($days, mktime(0, 0, 0, $date[1], $date[2], $date[0]));
$MTD = date('Y-m-01', strtotime('0 month'));
$M1 = date('Y-m-01', strtotime('-1 month'));
$M2 = date('Y-m-01', strtotime('-2 month'));
$M3 = date('Y-m-01', strtotime('-3 month'));
$rng = array();
$rng[$MTD] = strftime("%B, %Y", strtotime(" ", $time));
$rng[$M1] = strftime("%B, %Y", strtotime("first day of previous month", $time));
$rng[$M2] = strftime("%B, %Y", strtotime("-2 months", $time));
$rng[$M3] = strftime("%B, %Y", strtotime("-3 months", $time));
?>
Here $MTD ,$M1,$M2,$M3 will give date in the form of "dd-mm-yyyy" and $rng[$MTD], $rng[$M1],$rng[$M2],$rng[$M3] give date in the form of"Name of Month,year" => (i.e August,2016)

Categories