Get financial year by given month - php

Financial year starts on 01 April and we are in January so January falls into year 2020 and so is February and March. So if I use April now, it should fall in to year 2019. Currently I used the following code but it doesn't work the way I want it
$month =01;
if ( $month >= 4 ) {
$year = date('Y');
}
else {
$year = date('Y')-1;
}
echo $year;
SO when I set the month to 1 which is January, the year shows as 2019 but it should really be 2020.
Is there anyway to set the year in PHP so when the months will start from April and ends end of March so when I enter a month, I will get the correct year?

Try something like this: Carbon::now()->subMonths(3)->year
This way January, February, and March dates will return 2019, and April will start returning 2020 as year.

I think i managed to fix the issue. Any comments is welcomed
$month =01;
$current_month = date('m');
if ($current_month >= '01' && $current_month < '4'){
if ($month >= '01' && $month < '04'){
$year = date('Y');
}
if ($month >= 4){
$year = date('Y')-1;
}
}
if ($current_month >= 4){
if ($month >= 4){
$year = date('Y');
}
if ($month < 4){
$year = date('Y')+1;
}
}
echo $year;

I hope this will solve your issue
$date=date_create("2020-05-13");
echo "<br> Month: ".date_format($date,"m");
if (date_format($date,"m") >= 4) {//On or After April (FY is current year - next year)
$financial_year = (date_format($date,"Y")) . '-' . (date_format($date,"y")+1);
} else {//On or Before March (FY is previous year - current year)
$financial_year = (date_format($date,"Y")-1) . '-' . date_format($date,"y");
}
echo "<br> FY ".$financial_year;

Something along the lines :
$now = strtotime('now');
$firstApril = strtotime('1st april');
$year = ($now < $firstApril) ? date('Y')-1 : $date('Y');
return $year;
This would compare the timestamp and if its less than 1st april of this year than it will get the previous year.

you can try this:
$month =01;
if($month>=4&&$month<=12){
$year=date('Y')-1;
}
if($month>=1&&$month<=3){
$year=date('Y');
}
echo $year;

It's not a direct answer, but if you handle multiple financial/transactional data for a financial year for your business, you probably are in a similar position as I was a few years back.
Feel free to check this library -> https://github.com/RoussKS/financial-year
It would be an overkill for a single checking (even though considerably lightweight), but if you have more requirements, it could be useful.
Requires the start of the financial year date and the type of the financial year (in your case, it's calendar as per library's spec) and provides ending date, period ranges and more.
Returns a DateTimeImmutable object or a DatePeriod depending the method used (get a date, period, or week for business type financial year only)
In your case, the use case would be like
require_once __DIR__ . '/vendor/autoload.php';
// DateTimeAdapter
// If instantiating with string, it must be of ISO-8601 format 'YYYY-MM-DD'
$startDate = new \DateTime('2019-04-01');
$fy = new \RoussKS\FinancialYear\DateTimeAdapter('calendar', $startDate);
// January is the 10th period for a financial year based on 12 periods starting at 2019-04-01.
// First date of the period would give you 2020-01-01
echo $fy->getFirstDateOfPeriodById(10)->format('Y'); // 2020
Feel free to test and advise

Here's how to get the start date for the current financial year (start date 1st April).
public function getFinancialYear(){
$today = Carbon::today();
$month = $today->format('m');
$year = $today->format('Y');
$firstApril = 'first day of April '.$year;
$financialYear = new Carbon($firstApril);
if($month < 4){
$financialYear->subYear();
}
return $financialYear;
}

function fascal_year(){
$today_year = date("Y");
$today_month = date("m");
$fascal_year = "";
if($today_month <= 6){
$fascal_year = ($today_year - 1) ."-". $today_year;
}else{
$fascal_year = $today_year."-".($today_year + 1);
}
return $fascal_year;
}

Related

Make the number to start from 1 if it is greater than 12 with PHP

I am trying to convert English Date with Nepali. I have done the following so far:
function nepaliYear($year){
$year = date('Y', strtotime($year)) + 56;
$month = date('m', strtotime($year)) + 8;
$days = date('d', strtotime($year)) + 15;
if($month > 12){
$year = $year + 1;
$month = date('H', strtotime($month)); //need help here
}
return $year.'-'.$month.'-'.$days;
}
I want the number to continue from 1 if the month is greater than 12. Suppose this month is July which is 7 and if I do 7+8 it gives 15. How to make month to 03? I tried to achieve this with H in the date function as the hours will be in 12 hours.
I hope you understood my question. Will be ready add an explanation if asked. Thank you.
There is a simple solution that you can do.
if($month > 12){
$year = $year + 1;
$month = $month - 12;
}
Since you have asked about converting the days in the comment section,
You know that there are leap years (February has 29 days sometimes). And for example July and August have 31 days. You can't say generally "convert 144 days to months" because it's different for every month.
For ex:
Lets imagine you need to convert 94 days into months.
<?php
$start_date = new DateTime(date("Y/m/d"));
$end_date = new DateTime(date("Y/m/d",strtotime("+94")));
$date_diff = date_diff($start_date,$end_date);
echo "$date_diff->m months $dd->d days";
?>
for start_date you can use a specific date. also for end_date this is the correct way, so every leap year and everything is observed!

How can I make date("W") start in Sunday and end on saturday? [duplicate]

I need to get week number in php where week should be calculated from sunday. By default its from monday. Please help me to find a way how to get week number considering sunday as starting day.
In php manual
ISO-8601 week number of year, weeks starting on Monday (added in PHP 4.1.0)
But I need to get week number of year, weeks starting on sunday.
thanks
Try this:
$week = intval(date('W'));
if (date('w') == 0) { // 0 = Sunday
$week++;
}
echo $week;
Not sure if the logic is right though;
The first solution is not correct on Jan 01, 2017 or any year that begins on a Sunday.
Try this:
$date = date('Y-m-d');
echo strftime("%U", strtotime($date ) );
To expand on silkfire answer and allow for it wrapping around years
if($date->format('w') == 0){
if(date('W',strtotime($date->format('Y')."-12-31"))==52 and $date->format('W') == 52){
$week = 1;
}
elseif(date('W',strtotime($date->format('Y')."-12-31"))==53 and $date->format('W') == 53){
$week = 1;
}
else{
$week++;
}
}
Try this one. to get sunday day must -1 day.
$date = "2015-05-25";
echo date("W", strtotime("-1 day",strtotime($date)));
You should try with strftime
$week_start = new DateTime();
$week = strftime("%U"); //this gets you the week number starting Sunday
$week_start->setISODate(2012,$week,0); //return the first day of the week with offset 0
echo $week_start -> format('d-M-Y'); //and just prints with formatting
I solved this like this:
function getWeekOfYear( DateTime $date ) {
$dayOfweek = intval( $date->format('w') );
if( $dayOfweek == 0 ) {
$date->add(new DateInterval('P1D'));
}
$weekOfYear = intval( $date->format('W') );
return $weekOfYear;
}
I know this topic is old, but this is a shorter way to do it with elvis operator and "+7 day" expression for strtotime():
$week=date("W",strtotime(date("w")==1?"+7 day":"+0 day"));
if $date("w") returns true means today is a day between tuesday and sunday (1-6), so, we can return today week ('today').
if returns false, it means is monday (0), so, we should return the next day ('+1 week').
This way we don't need to care about last or first day of year or check if current year has 52 or 53 weeks.
Edited: the previous answer (and others in this topic) doesn't work for this year because januray 1st is monday, so, it needs to be 1 week ago (-1 week) excluding sunday (day 6).
date("W",strtotime(date("w")?'-7 day':'+0 day'));
I think a condition asking if januray 1st is monday could work, but I didn't test it yet, I will come back with an answer later
For a custom day you could use this:
$date = strtotime('2018-04-30'); // (it is monday)
if(date("w",strtotime(date('Y',$date).'-01-01'))==1){ // if first day of year is monday
$week = strtotime(date('w',$date)?"-7 day":"+0 day",$date); // and today is sunday, sub a week
$week = date("W",$week);
}else{ // if is not monday
$week = strtotime(date('w',$date)==1?"+7 day":"+0 day",$date); // and today is monday, add a week
$week = date("W",$week);
}
Building on #silkfire's answer:
$year = date('Y');
$week_no = date('W');
if (date('w') == 0) { // 0 = Sunday
$week_no++;
}
// We shifted the week but the week still starts on a Monday.
$weekStartDate = new DateTime();
$weekStartDate->setISODate($year,$week_no);
// Shift start date to Sunday
$weekStartDate->add(DateInterval::createFromDateString('-1 day'));
Tested in php 5.6 Debian 7
function getWeekNumber(\DateTime $_date)
{
$week = intval($_date->format('W'));
if(intval($_date->format('w')) == 0) {
$week = intval($_date->format('W')) == ( 52 + intval($_date->format('L')) ) ? 1 : $week + 1;
}
return $week;
}
I needed to ADD day instead of subtracting to get Alghi Fari's answer to work.
$date = "2022-11-13";
echo date("W", strtotime("+1 day",strtotime($date)));

Month duplication occurs when DateTime called on end of a 31 day month

I have some strange behaviour happening when I run the following on the last day of May (31st). If I change my system time to 30th May, or the last day of say, June (30th), it functions normally.
For some reason though, on the 31st, it will skip the next month (June), and instead replace it with July. So it will output July twice. Here is an example:
31 days in 05, 31 days in 07, 31 days in 07, 31 days in 08,
Code which generated the above
<?php
$datepicker_month_range = 3;
// create an array of dates for a number of months specified by the user. 0 is used for this month
for ($month = 0; $month <= $datepicker_month_range; $month++) {
$dt_dates = new DateTime();
$dt_dates->add(new DateInterval("P{$month}M")); // example, P1M == plus 1 month
$days_in_month = cal_days_in_month(CAL_GREGORIAN, $dt_dates->format('m'), $dt_dates->format('Y'));
echo $days_in_month." days in ".$dt_dates->format('m').", ";
for ($day = 1; $day <= $days_in_month; $day++) {
$date = $dt_dates->format('Y')."-".$dt_dates->format('m')."-".sprintf('%02d', $day); // leading zeros 05-..
$month_days[] = $date;
}
}
//print_r($month_days);
?>
Later on, if print_r($month_days) is run, the complete dates are outputted with July outputted twice like in the previous expression.
What is causing this behaviour?
Thanks.
Ok, after reading the comments, it seems this is a duplicate of PHP DateTime::modify adding and subtracting months
but here is how I got around the problem.
$month_beginning = $dt_dates->format('Y-m-01');
$dt_dates = new DateTime($month_beginning); // rollback the date to the first so we can increment months safely
All together
for ($month = 0; $month <= $datepicker_month_range; $month++) {
$dt_dates = new DateTime();
$month_beginning = $dt_dates->format('Y-m-01');
$dt_dates = new DateTime($month_beginning); // rollback the date to the first so we can increment months safely
$dt_dates->add(new DateInterval("P{$month}M")); // P1M == plus 1 month
$days_in_month = cal_days_in_month(CAL_GREGORIAN, $dt_dates->format('m'), $dt_dates->format('Y'));
//echo $days_in_month." days in ".$dt_dates->format('m').", ";
for ($day = 1; $day <= $days_in_month; $day++) {
$date = $dt_dates->format('Y')."-".$dt_dates->format('m')."-".sprintf('%02d', $day); // leading zeros 05-..
$month_days[] = $date; // holds dates for datepicker month ranges
}
}

date("F", strtotime(day-month-year)) printing out the wrong value for the second month of the year

Just out of curiosity, anyone know why
echo date("F", strToTime("$day-02-$year"));
would print out March, originally I thought it was a common off by one error but
echo date("F", strToTime("$day-01-$year"));
prints out January and
echo date("F", strToTime("$day-03-$year"));
prints out march, so I am unsure of what is actually going on here???
any ideas
You run this script today, so $day=30;?
So, if you try to get the 30th day of February, it returns you the 2nd day of March - or March 1st in leap years. Obviously because February doesn't have enough days...
$day = 30;
$year = 2014;
echo date("r", strToTime("$day-02-$year"));
Output:
Sun, 02 Mar 2014 00:00:00 +0100
It's not a bug, it's a feature.
My problem was defaulting the day as a "j" i just made the default 01 if there was no day set and it works now,
I have a calendar that I was going from month to month with simple buttons and the day was never set in my conditional statement I had that if the day was not set that the default was a lowercase j as soon as I changed that it responded with the correct name, So the answer to this question is to ensure that the default day is set to 1 if there is not going to be a day present such as when you are going from month to month
<?php
if (isSet($_GET['day'])) {
$day = $_GET['day'];
} else {
$day = date("01");
}
if (isSet($_GET['month'])) {
$month = $_GET['month'];
} else {
$month = date("n");
}
if (isSet($_GET['year'])){
$year = $_GET['year'];
} else {
$year = date("Y");
}
//calendar variable
$currentTimeStamp = strToTime("$day-$month-$year");
//get current month name
$monthName = date("F", $currentTimeStamp);
//get how many days are in the current month
$numDays = date("t", $currentTimeStamp);
//counter for calendar cells in loop
$counter = 0;
?>
like so!

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