Output current week number within month PHP - php

I have a PHP script to identify the current month and current week within that month.
For today, it should output 501 (i.e. 5th week of the 1st month), however right now it outputs 101.
Can someone explain why this is the case and how I can resolve? I feel I'm missing something obvious.
<?php
date_default_timezone_set("Europe/London");
function weekOfMonthFunction($date) {
$firstOfMonth = date("Y-m-01", strtotime($date));
return intval(date("W", strtotime($date))) - intval(date("W", strtotime($firstOfMonth)));
}
$week = weekOfMonthFunction($date2);
$week = $week + 1;
$month = date("m");
$week_month = $week.$month;
echo $week_month;

<?php
date_default_timezone_set("Europe/London");
function weekOfMonth() {
$now = time();
$week = date('W', $now);
$firstWeekOfMonth = date('W', strtotime(date('Y-m-01', $now)));
return 1 + ($week < $firstWeekOfMonth ? $week : $week - $firstWeekOfMonth);
}
$week = weekOfMonth();
$week_month = $week . date("m");
echo $week_month;
501
Try it online!

You've fixed the date to Y-m-01 instead of Y-m-d from the parameter date.
How about this alternative?
function weekOfMonthFunction($date) {
list($d, $m) = explode('-', date("d-m", strtotime($date)));
return intval(ceil($d/7).str_pad($m, 1, '0', STR_PAD_LEFT));
}
echo weekOfMonthFunction('2021-01-25'); //Give 401
echo weekOfMonthFunction('2020-01-29'); //Gives 501
Explanation:
Date of month divided by 7 rounded up to get week number prepended to month number with a padded 0

Related

PHP How to divide weeks into days

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.

PHP subtract 1 month from date formatted with date ('m-Y')

I'm trying to subtract 1 month from a date.
$today = date('m-Y');
This gives: 08-2016
How can I subtract a month to get 07-2016?
<?php
echo $newdate = date("m-Y", strtotime("-1 months"));
output
07-2016
Warning! The above-mentioned examples won't work if call them at the end of a month.
<?php
$now = mktime(0, 0, 0, 10, 31, 2017);
echo date("m-Y", $now)."\n";
echo date("m-Y", strtotime("-1 months", $now))."\n";
will output:
10-2017
10-2017
The following example will produce the same result:
$date = new DateTime('2017-10-31 00:00:00');
echo $date->format('m-Y')."\n";
$date->modify('-1 month');
echo $date->format('m-Y')."\n";
Plenty of ways how to solve the issue can be found in another thread: PHP DateTime::modify adding and subtracting months
Try this,
$today = date('m-Y');
$newdate = date('m-Y', strtotime('-1 months', strtotime($today)));
echo $newdate;
Depending on your PHP version you can use DateTime object (introduced in PHP 5.2 if I remember correctly):
<?php
$today = new DateTime(); // This will create a DateTime object with the current date
$today->modify('-1 month');
You can pass another date to the constructor, it does not have to be the current date. More information: http://php.net/manual/en/datetime.modify.php
I used this to prevent the "last days of month"-error. I just use a second strtotime() to set the date to the first day of the month:
<?php
echo $newdate = date("m-Y", strtotime("-1 months", strtotime(date("Y-m")."-01")));
if(date("d") > 28){
$date = date("Y-m", strtotime("-".$loop." months -2 Day"));
} else {
$date = date("Y-m", strtotime("-".$loop." months"));
}
$lastMonth = date('Y-m', strtotime('-1 MONTH'));
First change the date format m-Y to Y-m
$date = $_POST('date'); // Post month
or
$date = date('m-Y'); // currrent month
$date_txt = date_create_from_format('m-Y', $date);
$change_format = date_format($date_txt, 'Y-m');
This code minus 1 month to the given date
$final_date = new DateTime($change_format);
$final_date->modify('-1 month');
$output = $final_date->format('m-Y');
Try this,
$effectiveDate = date('2018-01'); <br>
echo 'Date'.$effectiveDate;<br>
$effectiveDate = date('m-y', strtotime($effectiveDate.'+-1 months'));<br>
echo 'Date'.$effectiveDate;
$currentMonth = date('m', time());
$currentDay = date('d',time());
$currentYear = date('Y',time());
$lastMonth = $currentMonth -1;
$one_month_ago=mkdate(0,0,0,$one_month_ago,$currentDay,$currentYear);
This could be rewritten more elegantly, but it works for me
I realize this is an old post, but I've been solving the same issue, and here is what I came up with to account for all the variability. This function is just trying to get relative dates, so same day of prior month, or last day of month if you are on the last day, regardless of exactly how many days a month has. So goal is given '2010-03-31' and subtract a month, we should output '2010-02-28'.
private function subtractRelativeMonth(DateTime $incomingDate): DateTime
{
$year = $incomingDate->format('Y');
$month = $incomingDate->format('m');
$day = $incomingDate->format('d');
$daysInOldMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
if ($month == 1) { //It's January, so we have to go back to December of prior year
$month = 12;
$year--;
} else {
$month--;
}
$daysInNewMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
if ($day > $daysInNewMonth && $month == 2) { //New month is Feb
$day = $daysInNewMonth;
}
if ($day > 29 && $daysInOldMonth > $daysInNewMonth) {
$day = $daysInNewMonth;
}
$adjustedDate = new \DateTime($year . '-' . $month . '-' . $day);
return $adjustedDate;
}

extract total hours in a particular MONTH and YEAR, taking into account leap years, using PHP

I need to extract the total hours in a any month, given just the MONTH and the YEAR, taking into account leap years.
Here is my code so far...
$MonthName = "January";
$Year = "2013";
$TimestampofMonth = strtotime("$MonthName $Year");
$TotalMinutesinMonth = $TimestampofMonth / 60 // to convert to minutes
$TotalHoursinMonth = $TotalMinutesinMonth / 60 // to convert to hours
Just work out the number of days in the month and then multiply by 24, like so:
// Set the date in any format
$date = '01/01/2013';
// another possible format etc...
$date = 'January 1st, 2013';
// Get the number of days in the month
$days = date('t', strtotime($date));
// Write out the days
echo $days;
You can do this:
<?php
$MonthName = "January";
$Year = "2013";
$days = date("t", strtotime("$MonthName 1st, $Year"));
echo $days * 24;
You can use DateTime::createFromFormat since you don't have day
$date = DateTime::createFromFormat("F Y", "January 2013");
printf("%s hr(s)",$date->format("t") * 24);
Well if you are looking at working day its a different approach
$date = "January 2013"; // You only know Month and year
$workHours = 10; // 10hurs a day
$start = DateTime::createFromFormat("F Y d", "$date 1"); // added first
printf("%s hr(s)", $start->format("t") * 24);
// if you are only looking at working days
$end = clone $start;
$end->modify(sprintf("+%d day", $start->format("t") - 1));
$interval = new DateInterval("P1D"); // Interval
var_dump($start, $end);
$hr = 0;
foreach(new DatePeriod($start, $interval, $end) as $day) {
// Exclude sarturday & Sunday
if ($day->format('N') < 6) {
$hr += $workHours; // add working hours
}
}
printf("%s hr(s)", $hr);
<?php
function get_days_in_month($month, $year)
{
return $month == 2 ? ($year % 4 ? 28 : ($year % 100 ? 29 : ($year %400 ? 28 : 29))) : (($month - 1) % 7 % 2 ? 30 : 31);
}
$month = 4;
$year = 2013;
$total_hours = 24 * get_days_in_month($month, $year);
?>
you can use above function to retrieve total days in a month taking into account leap year and then multiply the value to 24
plus, you can also use a cal_days_in_month function but it only supports PHP builds of PHP 4.0.7 and higher.
and if you are using the above "get_day_in_month" then you need to parse the string into integer which can be done like this
FOR MONTH
<?php
$date = date_parse('July');
$month_int = $date['month'];
?>
FOR YEAR
<?php
$year_string = "2013"
$year_int = (int) $year_string
?>

Given a day and month, return the most recent date of that day and month in the form day-month-year

Given a date like "4 May", how do I get the most recent 4th May in the format "4 May, 2010"?
If the day/month combination has not yet occurred this year, it should show the date for last year (e.g. "31 December" should translate to "31 December, 2009").
Try something like this:
$cmpDate = strtotime('March 15');
$cmpDay = date('d',$cmpDate);
$cmpMonth = date('m',$cmpDate);
$currentDay = date('d');
$currentMonth = date('m');
if(($currentDay > $cmpDay && $currentMonth == $cmpMonth) || ($cmpMonth > $currentMonth) {
// Add one year
}
my tip is to use date('z') (= day of the year) for comparisons
$date = '11 Aug';
$ts = strtotime($date);
$recent = date('z', $ts) <= date('z') ? $ts : strtotime("$date previous year");
Try this (this is psuedo-code):
<?php
$currMonth = (int)date("m");
$currentDate = (int)date("d");
$currentYear = (int)date("Y");
// extract date and month from given date as needed,
// call it $givenMonth, $givenDate
if (($givenMonth <= $currMonth) && ($givenDate <= $givenDate)) {
$givenYear = $currentYear;
}
else {
$givenYear = $currYear - 1;
}
echo "Given date is: " + $currentMonth + "/" + $currentDate + "/" + $currentYear;
?>
function recentizer($date) {
$year = date('Y', time());
return (strtotime($date) < time()) ?
$date . ' ' . $year : $date . ' ' . ($year-1);
}
Example:
$dates = array('4 May', '6 February', '23 December');
foreach ($dates as $date) {
echo recentizer($date) . "\n";
}
Outputs:
4 May 2010
6 February 2010
23 December 2009
You can use this function:
echo date('m/d/y',strtotime('5 Sep',strtotime('-1 year'.str_repeat(' +1 year',(time()-strtotime('5 Sep'))/abs(time()-strtotime('5 Sep')) ) )) );
and change '5 Sep' to whatever date you want.
It works by setting the base year in strtotime to the current prior year (ie, '-1 year'), and then adjusts back to the current year (ie '+1 year') if the current time is greater than the time provided in your string.

How to find first day of the next month and remaining days till this date with PHP

How can I find first day of the next month and the remaining days till this day from the present day?
Thank you
Create a timestamp for 00:00 on the first day of next month:
$firstDayNextMonth = strtotime('first day of next month');
The number of days til that date is the number of seconds between now and then divided by (24 * 60 * 60).
$daysTilNextMonth = ($firstDayNextMonth - time()) / (24 * 3600);
$firstDayNextMonth = date('Y-m-d', strtotime('first day of next month'));
For getting first day after two months from current
$firstDayAfterTwoMonths = date('Y-m-d', strtotime('first day of +2 month'));
You can use DateTime object like this to find out the first day of next month like this:
$date = new DateTime('first day of next month');
You can do this to know how many days left from now to the first day of next month:
$date = new DateTime('now');
$nowTimestamp = $date->getTimestamp();
$date->modify('first day of next month');
$firstDayOfNextMonthTimestamp = $date->getTimestamp();
echo ($firstDayOfNextMonthTimestamp - $nowTimestamp) / 86400;
The easiest and quickest way is to use strtotime() which recognizes 'first day next month';
$firstDayNextMonth = date('Y-m-d', strtotime('first day next month'));
Since I googled this and came to this answer, I figured I'd include a more modern answer that works for PHP 5.3.0+.
//Your starting date as DateTime
$currentDate = new DateTime(date('Y-m-d'));
//Add 1 month
$currentDate->add(new DateInterval('P1M'));
//Get the first day of the next month as string
$firstDayOfNextMonth = $currentDate->format('Y-m-1');
You can get the first of the next month with this:
$now = getdate();
$nextmonth = ($now['mon'] + 1) % 13 + 1;
$year = $now['year'];
if($nextmonth == 1)
$year++;
$thefirst = gmmktime(0, 0, 0, $nextmonth, $year);
With this example, $thefirst will be the UNIX timestamp for the first of the next month. Use date to format it to your liking.
This will give you the remaining days in the month:
$now = getdate();
$months = array(
31,
28 + ($now['year'] % 4 == 0 ? 1 : 0), // Support for leap years!
31,
30,
31,
30,
31,
31,
30,
31,
30,
31
);
$days = $months[$now['mon'] - 1];
$daysleft = $days - $now['mday'];
The number of days left will be stored in $daysleft.
Hope this helps!
$firstDayNextMonth = date('Y-m-d', mktime(0, 0, 0, date('m')+1, 1, date('Y')));
As another poster has mentioned the DateInterval object does not give accurate results for the next month when you use dates such as 1/31/2016 or 8/31/2016 as it skips the next month. My solution was to still use the DateInterval object but reformat your current date to be the first day of the current month prior to utilizing the DateInterval.
$currentDate = '8/31/2016';
$date = new DateTime(date("n", strtotime($currentDate))."/1/".date("Y", strtotime($currentDate)));
//add 1 month
$date->add(new DateInterval('P1M'));
$currentDate=$date->format('m/1/Y');
echo($currentDate);
easiest way to get the last day of the month
date('Y-m-d', mktime(0, 0, 0, date('m')+1, 1, date('Y')));
I took mattbasta's approach because it's able to get the 'first day of next month' with a given date, but there is a tiny problem in calculating the $nextmonth. The fix is as below:
$now = getdate();
$nextmonth = ($now['mon'] + 1) % 13 + 1;
$year = $now['year'];
if($nextmonth == 1)
$year++;
else
$nextmonth--;
$thefirst = gmmktime(0, 0, 0, $nextmonth, $year);
I initially thought about using a DateInterval object (as discussed above in another answer) but it is not reliable. For example, if the current DateTime is 31 January and then we add on a month (to get the next month) then it will skip February completely!
Here is my solution:
function start_of_next_month(DateTime $datetime)
{
$year = (int) $datetime->format('Y');
$month = (int) $datetime->format('n');
$month += 1;
if ($month === 13)
{
$month = 1;
$year += 1;
}
return new DateTime($year . '-' . $month . '-01');
}
Even easier way to get first and last day of next month
$first = strttotime("first day of next month");
$last = strttotime("last day of next month");
You could do something like this. To have this functionality, you need to make use of a php library available in https://packagist.org/packages/ishworkh/navigable-date.
With that is really easy to do what you're asking for here.
For e.g:
$format = 'Y-m-d H:i:s';
$Date = \NavigableDate\NavigableDateFacade::create('2017-02-24');
var_dump($Date->format($format));
$resetTime = true;
$resetDays = true;
$NextMonth = $Date->nextMonth($resetTime, $resetDays);
var_dump($NextMonth->format($format));
$DayUntilFirstOfNextMonth = $NextMonth->getDifference($Date);
var_dump('Days left:' . $DayUntilFirstOfNextMonth->format('%d'));
gives you ouput:
string(19) "2017-02-24 00:00:00"
string(19) "2017-03-01 00:00:00"
string(11) "Days left:5"
Note: Additionally this library let you navigate through dates by day(s), week(s), year(s) forward or backward. For more information look into its README.
(PHP 5 >= 5.5.0, PHP 7, PHP 8)
To get the first day of next month a clean solution:
<?php
$date = new DateTimeInmutable('now');
$date->modify('first day of next month');//here the magic occurs
echo $date->format('Y-m-d') . '\n';
Since you just want to calculate it I suggest using DateTimeInmutable class.
using the class DateTime and $date->modify('first day of next month'); will modify your original date value.
$month = date('m')+1;
if ($month<10) {
$month = '0'.$month;
}
echo date('Y-').$month.'-01';
Simplest way to achieve this. You can echo or store into variable.
I came up with this for my needs:
if(date('m') == 12) { $next_month = 1; } else { $next_month = date('m')+1; }
if($next_month == 1) { $year_start = date('Y')+1; } else { $year_start = date('Y'); }
$date_start_of_next_month = $year_start . '-' . $next_month . '-01 00:00:00';
if($next_month == 12) { $month_after = 1; } else { $month_after = $next_month+1; }
if($month_after == 1) { $year_end = date('Y')+1; } else { $year_end = date('Y'); }
$date_start_of_month_after_next = $year_end . '-' . $month_after . '-01 00:00:00';
Please note that instead of getting $date_end_of_next_month I chose to go with a $date_start_of_month_after_next date, it avoids the hassles with leap years and months containing different number of days.
You can simply use the >= comparaision sign for $date_start_of_next_month and the < one for $date_start_of_month_after_next.
If you prefer a timestamp format for the date, from there you will want to apply the strtotime() native function of PHP on these two variables.
You can use the php date method to find the current month and date, and then you would need to have a short list to find how many days in that month and subtract (leap year would require extra work).

Categories