I'm trying to get a week range for the month, I've somewhat accomplished what I'm looking for but I'd like the code to be more reliable. The data ranges are going to be used to some MySQL queries where I can filter out data by data range.
What I'd like to achieve is to get something like the Windows 10 calendar. So the result is
2020-03-01 to 2020-03-01
2020-03-02 to 2020-03-08
2020-03-09 to 2020-03-15
2020-03-16 to 2020-03-22
2020-03-23 to 2020-03-29
2020-03-30 to 2020-03-31
CODE
$start_date = date("Y-m-d", strtotime("first day of this month"));
$end_date = date("Y-m-d", strtotime("last day of this month"));
function getWeekDates($date, $start_date, $end_date) {
$week = date('W', strtotime($date));
$year = date('Y', strtotime($date));
$from = date("Y-m-d", strtotime("{$year}-W{$week}+1"));
if($from <= $start_date){
$from = $start_date;
}
$to = date("Y-m-d", strtotime("{$year}-W{$week}-7"));
if($to >= $end_date){
$to = $end_date;
}
echo $from." to ".$to.'<br>';
}
for($date = $start_date; $date <= $end_date; $date = date('Y-m-d', strtotime($date. ' + 7 day'))){
echo getWeekDates($date, $start_date, $end_date);
echo "\n";
}
Which results in
It's missing the last two days of the month (30 and 31).
2020-03-01 to 2020-03-01
2020-03-02 to 2020-03-08
2020-03-09 to 2020-03-15
2020-03-16 to 2020-03-22
2020-03-23 to 2020-03-29
You can use DateTime objects to do this more readily, setting a start time as the first Monday on or before the start of the month, and then adding a week at a time until it is past the end of the month:
$month_start = new DateTime("first day of this month");
$month_end = new DateTime("last day of this month");
// find the Monday on/before the start of the month
$start_date = clone $month_start;
$start_date->modify((1 - $start_date->format('N')) . ' days');
while ($start_date <= $month_end) {
echo max($month_start, $start_date)->format('Y-m-d') . ' to ' . min($start_date->modify('+6 days'), $month_end)->format('Y-m-d') . "\n";
$start_date->modify('+1 day');
}
Output:
2020-03-01 to 2020-03-01
2020-03-02 to 2020-03-08
2020-03-09 to 2020-03-15
2020-03-16 to 2020-03-22
2020-03-23 to 2020-03-29
2020-03-30 to 2020-03-31
Demo on 3v4l.org
Related
I want dates like current week dates from Monday to Wednesday and last week dates from last week Monday to last week Wednesday
I have tried this code
function last_to_last_week_date(){
$previous_week = strtotime("-2 week +1 day");
$start_week = strtotime("last monday",$previous_week);
$end_week = strtotime("next sunday",$start_week);
$start_week = date("Y-m-d",$start_week);
$end_week = date("Y-m-d",$end_week);
return $start_week.' '.$end_week ;
}
function last_week_date(){
$previous_week = strtotime("-1 week +1 day");
$start_week = strtotime("last monday",$previous_week);
$end_week = strtotime("next sunday",$start_week);
$start_week = date("Y-m-d",$start_week);
$end_week = date("Y-m-d",$end_week);
return $start_week.' '.$end_week ;
}
but with this, I have received last week dates and last to last week dates
can anybody help me with this
You can simply fix 2 rows in your code:
$end_week = strtotime("next wednesday",$start_week); // <-- "next wednesday"
And for the current dates:
$previous_week = strtotime("+1 day");
Demo
Output:
2020-01-20 2020-01-22
2020-01-27 2020-01-29
DRY
You can simplify your code. Use one method in each of two:
function optimDate($prev_w){
$start_week = strtotime("last monday",$prev_w);
$end_week = strtotime("next wednesday",$start_week);
$start_week = date("Y-m-d",$start_week);
$end_week = date("Y-m-d",$end_week);
return $start_week.' '.$end_week ;
}
And these two method become like
function last_week_date(){
return optimDate(strtotime("-1 week +1 day"));
}
function curr_week_date(){
return optimDate(strtotime("+1 days"));
}
Demo
In fact, this also could be optimized.
I want dates like if today is Tuesday then I want a date from starting of this week to the current day and get last week date from starting of last week to the current day like if today is 11-02-2020 and Tuesday then I want date like 10-02-2020 11-02-2020 and last week dates like 03-02-2020 04-02-2020
for that, I have used below functions
function last_week_date(){
date_default_timezone_set("Asia/Kolkata");
$day = date("l");
$previous_week = strtotime("-1 week +1 day");
$start_week = strtotime("last monday",$previous_week);
$end_week = strtotime("next $day",$start_week);
$start_week = date("Y-m-d",$start_week);
$end_week = date("Y-m-d",$end_week);
return $start_week.' '.$end_week ;
}
function this_week_date(){
date_default_timezone_set("Asia/Kolkata");
$day = date("l");
$previous_week = strtotime("+1 day");
$start_week = strtotime("last monday",$previous_week);
$end_week = strtotime("next $day",$start_week);
$start_week = date("Y-m-d",$start_week);
$end_week = date("Y-m-d",$end_week);
return $start_week.' '.$end_week ;
}
but with this, I have received dates of the full week not till a particular day
can anybody help me with this
This function will give you the results you want. You can simply pass it a parameter which is the number of weeks forward or backward to shift the dates to get this weeks/last weeks/next weeks days:
function week_date($weeks = 0) {
$start = new DateTime("monday this week");
$end = new DateTime();
$start->modify("$weeks weeks");
$end->modify("$weeks weeks");
return $start->format('Y-m-d') . ' ' . $end->format('Y-m-d');
}
To call, use
echo week_date() . "\n"; // this week
echo week_date(-1) . "\n"; // last week
echo week_date(1) . "\n"; // next week
Output (as of Monday 2020-02-10):
2020-02-10 2020-02-10
2020-02-03 2020-02-03
2020-02-17 2020-02-17
Demo on 3v4l.org
Here a simple code of
date to week_number of year and now. How can I get start_date and end_date of week_number
$date_string = "2012-12-30";
echo "Weeknummer: " . date("W", strtotime($date_string));
There is many ways to do it, here is one.
I use "N" of date to determine what day the selected day is and use strtotimes way of understanding simple text to find previous or next Monday/Sunday.
$date_string = "2018-01-27";
$w =date("W", strtotime($date_string));
$N =date("N", strtotime($date_string));
If($N == 1){ // if monday
$monday = $date_string;
$sunday = date("Y-m-d", strtotime("next Sunday $date_string"));
}Elseif($N ==7){ // if sunday
$monday = date("Y-m-d", strtotime("previous Monday $date_string"));
$sunday = $date_string;
}Else{// any other weekday
$monday = date("Y-m-d", strtotime("previous Monday $date_string"));
$sunday = date("Y-m-d", strtotime("next Sunday $date_string"));
}
echo "Weeknummer: $w.\nMonday: $monday.\nSunday: $sunday.";
Output:
Weeknummer: 52.
Monday: 2012-12-24.
Sunday: 2012-12-30.
https://3v4l.org/UDoqF
You can use this:
<?php
$date_string = "2012-12-30";
$weekNumber = date("W", strtotime($date_string));
echo "Weeknummer: ".$weekNumber;
echo '</br>';
// get the year
$year = date("Y", strtotime($date_string));
// set the date string for the week number
$dateWeek = $year.'-W'.$weekNumber;
// increase the weekNumber to the next
$weekNumber = intval($weekNumber);
$weekNumber += 1;
// if it is lower than 10 add preceeding 0
if($weekNumber < 10) $weekNumber = '0'.$weekNumber;
// set the date string for the next week number
$dateWeekNext = $year.'-W'.$weekNumber;
echo '</br>';
// get the first day of the week
echo date('Y-m-d', strtotime($dateWeek));
echo '</br>';
// get the day before the first day of the next week
echo date('Y-m-d', strtotime($dateWeekNext . ' -1 day'));
?>
This outputs:
Weeknummer: 52
2012-12-24
2012-12-30
how can I get last week' date range in php ?
see my codes bellow:
<?php
function get_last_week_dates(){
// how can i get the date range last week ?
// ex: today is 2014-2-8
// the week date range of last week should be '2014-1-26 ~ 2014-2-1'
}
?>
You can use strtotime()
$previous_week = strtotime("-1 week +1 day");
$start_week = strtotime("last sunday midnight",$previous_week);
$end_week = strtotime("next saturday",$start_week);
$start_week = date("Y-m-d",$start_week);
$end_week = date("Y-m-d",$end_week);
echo $start_week.' '.$end_week ;
UPDATE
Changed the code to handle sunday. If the current day is sunday then - 1 week will be previous sunday and again getting previous sunday for that will go the one week back.
$previous_week = strtotime("-1 week +1 day");
In addition if we need to find the current week and next week date
range we can do as
Current week -
$d = strtotime("today");
$start_week = strtotime("last sunday midnight",$d);
$end_week = strtotime("next saturday",$d);
$start = date("Y-m-d",$start_week);
$end = date("Y-m-d",$end_week);
Next Week -
$d = strtotime("+1 week -1 day");
$start_week = strtotime("last sunday midnight",$d);
$end_week = strtotime("next saturday",$d);
$start = date("Y-m-d",$start_week);
$end = date("Y-m-d",$end_week);
Simply use
date("m/d/Y", strtotime("last week monday"));
date("m/d/Y", strtotime("last week sunday"));
It will give the date of Last week's Monday and Sunday.
you need you use strtotime function for this
<center>
<?php
function get_last_week_dates()
{
// how can i get the date range last week ?
// ex: today is 2014-2-8
// the week date range of last week should be '2014-1-26 ~ 2014-2-1'
$startdate = "last monday";
if (date('N') !== '1')
{
// it's not Monday today
$startdate .= " last week";
}
echo "<br />";
$day = strtotime($startdate);
echo date('r', $day);
echo "<br />";
$sunday = strtotime('next monday', $day) - 1;
echo date('r', $sunday);
}
get_last_week_dates();
?>
</center>
Well just for the fun of trying to solve this:
date_default_timezone_set('UTC');
$firstDayOfLastWeek = mktime(0,0,0,date("m"),date("d")-date("w")-7);
$lastDayOfLastWeek = mktime(0,0,0,date("m"),date("d")-date("w")-1);
echo("Last week began on: ".date("d.m.Y",$firstDayOfLastWeek));
echo("<br>");
echo("Last week ended on: ".date("d.m.Y",$lastDayOfLastWeek));
This should do the trick
$startWeek = date('Y-m-d',strtotime("Sunday Last Week"));
$endWeek = date('Y-m-d',strtotime("Sunday This Week"));
this would not work if ran on a Monday. It would get last Sunday (the day before) to the next Sunday. So using Abhik Chakraborty's method with the above:
$startTime = strtotime("last sunday midnight",$previous_week);
$endTime = strtotime("next sunday midnight",$startTime);
$startDate = date('Y-m-d 00:00:00',$startTime);
$endDate = date('Y-m-d 23:59:59',$endTime);
This will now give
start = 2014-08-10 00:00:00
endDate = 2014-08-17 23:59:59
I know this is old but here's a much more succinct way of doing it:
$startDate = date("m/d/y", strtotime(date("w") ? "2 sundays ago" : "last sunday"));
$endDate = date("m/d/y", strtotime("last saturday"));
echo $startDate . " - " . $endDate
This one will produce the proper result and handles the Monday issue
<?php
$monday = strtotime("last monday");
$monday = date('W', $monday)==date('W') ? $monday-7*86400 : $monday;
$sunday = strtotime(date("Y-m-d",$monday)." +6 days");
$this_week_sd = date("Y-m-d",$monday);
$this_week_ed = date("Y-m-d",$sunday);
echo "Last week range from $this_week_sd to $this_week_ed ";
?>
Most of those other solutions offered were off by one day.
If you want Sunday to Saturday for last week, this is the way to do it.
$start = date("Y-m-d",strtotime("last sunday",strtotime("-1 week")));
$end = date("Y-m-d",strtotime("saturday",strtotime("-1 week")));
echo $start. " to ".$end;
Carbon
$startOfTheWeek = Carbon::now()->subWeek(1)->startOfWeek();
$endOfTheWeek = Carbon::now()->subWeek(1)->endOfWeek();
From a specific date
$startOfTheWeek = Carbon::parse('2020-03-02')->subWeek(1)->startOfWeek();
$endOfTheWeek = Carbon::parse('2020-03-02')->subWeek(1)->endOfWeek();
Considering the week starts at Monday and ends at Sunday.
You can do this way.
First get the current timestamp and subtract the no.of days you want.
$curTime = time();
echo date("Y-m-d",$curTime);
echo "<br />";
echo date("Y-m-d",($curTime-(60*60*24*7)));
$lastWeekStartTime = strtotime("last sunday",strtotime("-1 week"));
$lastWeekEndTime = strtotime("this sunday",strtotime("-1 week"));
$lastWeekStart = date("Y-m-d",$lastWeekStartTime);
$lastWeekEnd = date("Y-m-d",$lastWeekEndTime);
In order to find the last week start date and end date you can follow up this code for doing it so.
It works on all intervals to find the date interval.
$Current = Date('N');
$DaysToSunday = 7 - $Current;
$DaysFromMonday = $Current - 1;
$Sunday = Date('d/m/y', strtotime("+ {$DaysToSunday} Days"));
$Monday = Date('d/m/y', strtotime("- {$DaysFromMonday} Days"));
If so you need to change it with the datatime() you can perform this function.
$date = new DateTime();
$weekday = $date->format('w');
$diff = 7 + ($weekday == 0 ? 6 : $weekday - 1); // Monday=0, Sunday=6
$date->modify("-$diff day");
echo $date->format('Y-m-d') . ' - ';
$date->modify('+6 day');
echo $date->format('Y-m-d');
Using Functions:
If you want to find the last week range with the help of the functions you can preform like this.
Function:
// returns last week's range
function last_week_range($date) {
$ts = strtotime("$date - 7 days");
$start = (date('w', $ts) == 0) ? $ts : strtotime('last sunday', $ts);
return array(
date('Y-m-d', $start),
date('Y-m-d', strtotime('next saturday', $start))
);
}
Usage:
$today=date();
print_r(last_week_range($today));
All the above functions that has been given will return the last week range irrespective of the start day of the week..
I have two columns in my db: start_date and end_date, which are both DATE types. My code is updating the dates as follows:
$today_date = date("Y-m-d");
$end_date = date("Y-m-d"); // date +1 month ??
$sql1 = "UPDATE `users` SET `start_date` = '".$today_date."', `end_date` = '".$end_date."' WHERE `users`.`id` ='".$id."' LIMIT 1 ;";
What is the best way to make $end_date equal to $start_date + one month? For example, 2000-10-01 would become 2000-11-01.
You can use PHP's strtotime() function:
// One month from today
$date = date('Y-m-d', strtotime('+1 month'));
// One month from a specific date
$date = date('Y-m-d', strtotime('+1 month', strtotime('2015-01-01')));
Just note that +1 month is not always calculated intuitively. It appears to always add the number of days that exist in the current month.
Current Date | +1 month
-----------------------------------------------------
2015-01-01 | 2015-02-01 (+31 days)
2015-01-15 | 2015-02-15 (+31 days)
2015-01-30 | 2015-03-02 (+31 days, skips Feb)
2015-01-31 | 2015-03-03 (+31 days, skips Feb)
2015-02-15 | 2015-03-15 (+28 days)
2015-03-31 | 2015-05-01 (+31 days, skips April)
2015-12-31 | 2016-01-31 (+31 days)
Some other date/time intervals that you can use:
$date = date('Y-m-d'); // Initial date string to use in calculation
$date = date('Y-m-d', strtotime('+1 day', strtotime($date)));
$date = date('Y-m-d', strtotime('+1 week', strtotime($date)));
$date = date('Y-m-d', strtotime('+2 week', strtotime($date)));
$date = date('Y-m-d', strtotime('+1 month', strtotime($date)));
$date = date('Y-m-d', strtotime('+30 days', strtotime($date)));
The accepted answer works only if you want exactly 31 days later. That means if you are using the date "2013-05-31" that you expect to not be in June which is not what I wanted.
If you want to have the next month, I suggest you to use the current year and month but keep using the 1st.
$date = date("Y-m-01");
$newdate = strtotime ( '+1 month' , strtotime ( $date ) ) ;
This way, you will be able to get the month and year of the next month without having a month skipped.
You do not actually need PHP functions to achieve this. You can already do simple date manipulations directly in SQL, for example:
$sql1 = "
UPDATE `users` SET
`start_date` = CURDATE(),
`end_date` = DATE_ADD(CURDATE(), INTERVAL 1 MONTH)
WHERE `users`.`id` = '" . $id . "';
";
Refer to http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_addtime
If you want a specific date in next month, you can do this:
// Calculate the timestamp
$expire = strtotime('first day of +1 month');
// Format the timestamp as a string
echo date('m/d/Y', $expire);
Note that this actually works more reliably where +1 month can be confusing. For example...
Current Day | first day of +1 month | +1 month
---------------------------------------------------------------------------
2015-01-01 | 2015-02-01 | 2015-02-01
2015-01-30 | 2015-02-01 | 2015-03-02 (skips Feb)
2015-01-31 | 2015-02-01 | 2015-03-03 (skips Feb)
2015-03-31 | 2015-04-01 | 2015-05-01 (skips April)
2015-12-31 | 2016-01-01 | 2016-01-31
Adding my solution here, as this is the thread that comes in google search. This is to get the next date of month, fixing any skips, keeping the next date within next month.
PHP adds current months total number of days to current date, if you do +1 month for example.
So applying +1 month to 30-01-2016 will return 02-03-2016. (Adding 31 days)
For my case, I needed to get 28-02-2016, so as to keep it within next month. In such cases you can use the solution below.
This code will identify if the given date's day is greater than next month's total days. If so It will subtract the days smartly and return the date within the month range.
Do note the return value is in timestamp format.
function getExactDateAfterMonths($timestamp, $months){
$day_current_date = date('d', $timestamp);
$first_date_of_current_month = date('01-m-Y', $timestamp);
// 't' gives last day of month, which is equal to no of days
$days_in_next_month = date('t', strtotime("+".$months." months", strtotime($first_date_of_current_month)));
$days_to_substract = 0;
if($day_current_date > $days_in_next_month)
$days_to_substract = $day_current_date - $days_in_next_month;
$php_date_after_months = strtotime("+".$months." months", $timestamp);
$exact_date_after_months = strtotime("-".$days_to_substract." days", $php_date_after_months);
return $exact_date_after_months;
}
getExactDateAfterMonths(strtotime('30-01-2016'), 1);
// $php_date_after_months => 02-03-2016
// $exact_date_after_months => 28-02-2016
You can use strtotime() as in Gazler's example, which is great for this case.
If you need more complicated control use mktime().
$end_date = mktime(date("H"), date("i"), date("s"), date("n") + 1, date("j"), date("Y"));
date("Y-m-d",strtotime("last day of +1 month",strtotime($anydate)))
date_trunc('month', now()) + interval '1 month'
date_trunc('month', now()) returns start date of month and + interval '1 month' add a month to date.
This function returns any correct number of months positively or negatively. Found in the comment section here:
function addMonthsToTime($numMonths = 1, $timeStamp = null){
$timeStamp === null and $timeStamp = time();//Default to the present
$newMonthNumDays = date('d',strtotime('last day of '.$numMonths.' months', $timeStamp));//Number of days in the new month
$currentDayOfMonth = date('d',$timeStamp);
if($currentDayOfMonth > $newMonthNumDays){
$newTimeStamp = strtotime('-'.($currentDayOfMonth - $newMonthNumDays).' days '.$numMonths.' months', $timeStamp);
} else {
$newTimeStamp = strtotime($numMonths.' months', $timeStamp);
}
return $newTimeStamp;
}
01-Feb-2014
$date = mktime( 0, 0, 0, 2, 1, 2014 );
echo strftime( '%d %B %Y', strtotime( '+1 month', $date ) );
I think this is similar to kouton's answer, but this one just takes in a timeStamp and returns a timestamp SOMEWHERE in the next month. You could use date("m", $nextMonthDateN) from there.
function nextMonthTimeStamp($curDateN){
$nextMonthDateN = $curDateN;
while( date("m", $nextMonthDateN) == date("m", $curDateN) ){
$nextMonthDateN += 60*60*24*27;
}
return $nextMonthDateN; //or return date("m", $nextMonthDateN);
}
I know - sort of late. But I was working at the same problem. If a client buys a month of service, he/she expects to end it a month later. Here's how I solved it:
$now = time();
$day = date('j',$now);
$year = date('o',$now);
$month = date('n',$now);
$hour = date('G');
$minute = date('i');
$month += $count;
if ($month > 12) {
$month -= 12;
$year++;
}
$work = strtotime($year . "-" . $month . "-01");
$avail = date('t',$work);
if ($day > $avail)
$day = $avail;
$stamp = strtotime($year . "-" . $month . "-" . $day . " " . $hour . ":" . $minute);
This will calculate the exact day n*count months from now (where count <= 12). If the service started March 31, 2019 and runs for 11 months, it will end on Feb 29, 2020. If it runs for just one month, the end date is Apr 30, 2019.
$nextm = date('m', strtotime('+1 month', strtotime(date('Y-m-01'))));
one way of doing this is- first getting last date of current month and then adding 1 day to it, to get next month's first date. This will prevent us from unintentional skipping of months which occurs while using '+1 month'.
$today_date = date("Y-m-d");
$last_date_of_month=date('Y-m-t',strtotime($today_date);//get last date of current month
$last_day_of_month_proper =strtotime($last_day_of_month);
$new_date=date('Y-m-d', strtotime('+1 day',$last_day_of_month_proper));
echo $new_date;