How to get year and month from a date - PHP - php

How to get year and month from a given date.
e.g. $dateValue = '2012-01-05';
From this date I need to get year as 2012 and month as January.

Use strtotime():
$time=strtotime($dateValue);
$month=date("F",$time);
$year=date("Y",$time);

Using date() and strtotime() from the docs.
$date = "2012-01-05";
$year = date('Y', strtotime($date));
$month = date('F', strtotime($date));
echo $month

Probably not the most efficient code, but here it goes:
$dateElements = explode('-', $dateValue);
$year = $dateElements[0];
echo $year; //2012
switch ($dateElements[1]) {
case '01' : $mo = "January";
break;
case '02' : $mo = "February";
break;
case '03' : $mo = "March";
break;
.
.
.
case '12' : $mo = "December";
break;
}
echo $mo; //January

I'm using these function to get year, month, day from the date
you should put them in a class
public function getYear($pdate) {
$date = DateTime::createFromFormat("Y-m-d", $pdate);
return $date->format("Y");
}
public function getMonth($pdate) {
$date = DateTime::createFromFormat("Y-m-d", $pdate);
return $date->format("m");
}
public function getDay($pdate) {
$date = DateTime::createFromFormat("Y-m-d", $pdate);
return $date->format("d");
}

You can use this code:
$dateValue = strtotime('2012-06-05');
$year = date('Y',$dateValue);
$monthName = date('F',$dateValue);
$monthNo = date('m',$dateValue);
printf("m=[%s], m=[%d], y=[%s]\n", $monthName, $monthNo, $year);

I will share my code:
In your given example date:
$dateValue = '2012-01-05';
It will go like this:
dateName($dateValue);
function dateName($date) {
$result = "";
$convert_date = strtotime($date);
$month = date('F',$convert_date);
$year = date('Y',$convert_date);
$name_day = date('l',$convert_date);
$day = date('j',$convert_date);
$result = $month . " " . $day . ", " . $year . " - " . $name_day;
return $result;
}
and will return a value: January 5, 2012 - Thursday

$dateValue = '2012-01-05';
$yeararray = explode("-", $dateValue);
echo "Year : ". $yeararray[0];
echo "Month : ". date( 'F', mktime(0, 0, 0, $yeararray[1]));
Usiong explode() this can be done.

$dateValue = '2012-01-05';
$year = date('Y',strtotime($dateValue));
$month = date('F',strtotime($dateValue));

I personally prefer using this shortcut. The output will still be the same, but you don't need to store the month and year in separate variables
$dateValue = '2012-01-05';
$formattedValue = date("F Y", strtotime($dateValue));
echo $formattedValue; //Output should be January 2012
A little side note on using this trick, you can use comma's to separate the month and year like so:
$formattedValue = date("F, Y", strtotime($dateValue));
echo $formattedValue //Output should be January, 2012

$dateValue = strtotime($q);
$yr = date("Y", $dateValue) ." ";
$mon = date("m", $dateValue)." ";
$date = date("d", $dateValue);

Related

How can I add a number of days after an end of the month in PHP?

My goal is to print a dueDate.
The due date formula is end of the month adding the days which is 7 on my example.
How can I make it possible?
My echoed value on my actual result is "Due date: 08/01/1970"
My expected result is "Due date: 07/06/2018"
$invoice_date = "11/05/2018";
$days = 7;
$is_invoice = false;
$date = date("d/m/Y", strtotime($invoice_date));
if ($is_invoice) {
$dueDate = date('d/m/Y', strtotime("+$day $days", strtotime($date)));
} else {
$dueDate = date('t/m/Y', strtotime($date));
$dueDate = date('d/m/Y', strtotime("+$day days", strtotime($date)));
}
echo "Due date: $dueDate";
Thanks in advance for the help
Try with the DateTime class:
$date = DateTime::createFromFormat('d/m/Y', '11/05/2018');
$dueDate = clone $date;
$dueDate->modify('+7 days');
echo 'Date : ' . $date->format('d/m/Y') . "\n";
echo 'Due : ' . $dueDate->format('d/m/Y') . "\n";
Output:
Date : 11/05/2018
Due : 18/05/2018
See it here: https://3v4l.org/BjUSK
Your coding logic is perfect except the undefined variable error
$invoice_date = "11/05/2018";
$day = 7;//in below statements used as day
$is_invoice = false;
$date = date("d/m/Y", strtotime($invoice_date));
if ($is_invoice) {
$dueDate = date('d/m/Y', strtotime("+$day days", strtotime($date)));
} else {
$dueDate = date('t/m/Y', strtotime($date));
$dueDate = date('d/m/Y', strtotime("+$day days", strtotime($date)));
}
echo "Due date: $dueDate";
Undefined variable $day;//Change days to day
I'd suggest you to use DateTime class and related functions:
$invoice_date = "11/05/2018";
$days = 7;
$input = date_create_from_format('d/m/Y', $invoice_date);
$result = $input->add(new DateInterval("P${days}D"));
$dueDate = $result->format('d/m/Y');
echo "Due date: $dueDate";
Output:
Due date: 11/05/2018
End of month + 7 days is how I read that ... correct me if I'm wrong:
$invoice_date= '11/05/2018';
$days= 7;
$dueDate= DateTime::createFromFormat('d/m/Y', $invoice_date);
$dueDate->modify('last day of this month')->modify('+7 days');
echo $dueDate->format('d/m/Y');
Invoice Date 11/5/2018 returns 7/6/2018
$invoice_date = "11-05-2018";
$day = 7;//in below statements used as day
$is_invoice = false;
$date = date("Y/m/d", strtotime($invoice_date));
if ($is_invoice) {
$dueDate = date('d/m/Y', strtotime($date. ' + '.$day.' days'));
} else {
$dueDate = date('Y-m-t', strtotime($date));
$dueDate = date('d/m/Y', strtotime($dueDate. ' + '.$day.' days'));
}
echo "Due date: ".$dueDate;

How to get the start date and end date when the year number and month number are known in php

I have the year number (ex: 2018) and the month number (Ex:04). I want to get the starting date and the ending date for that month. like
2018-04-01 and 2018-04-30
try this
$year = 2018;
$month = 4;
$date_start = date('Y-m-d', strtotime(date($year.'-'.$month).' first day of this month'));
$date_end = date('Y-m-d', strtotime(date($year.'-'.$month).'last day of this month'));
echo $date_start . ' and ' . $date_end;
$months_array = $this->getting_particular_months_dates($start_day_of_year, $end_day_of_year);
$arra1=array();
foreach ($months_array as $K => $v)
{
$year=explode( '-',$v['month'])[1];
$month=explode( '-',$v['month'])[0];
$arra1[]=$this->get_month_dates((int)$year,(int)$month);
}
return $arra1;
public function getting_particular_months_dates($year_start_date, $year_end_date)
{
$month_array = array();
$date1 = $year_start_date;
$date2 = $year_end_date;
$output = [];
$time = strtotime($date1);
$last = date('m-Y', strtotime($date2));
do {
$month = date('m-Y', $time);
$total = date('t', $time);
$output[] = [
'month' => $month,
'total' => $total,
];
$time = strtotime('+1 month', $time);
} while ($month != $last);
$month_array = $output;
return $month_array;
}
public function get_month_dates($year, $month)
{
$date_start = date('Y-m-d', strtotime(date($year . '-' . $month) . ' first day of this month'));
$date_end = date('Y-m-d', strtotime(date($year . '-' . $month) . 'last day of this month'));
$a = array('first_day' => $date_start, 'last_day' => $date_end);
return $a;
}

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

Error during third saturday date fetching

I want to fetch third Saturday and I am using php function for that, that i know.
But I am getting wrong data while fetching from an error.
Here is my code:
$frmdate = 2015-06-05;
$todate = 2015-08-31;
for ($date = strtotime($frmdate); $date <= strtotime($todate); $date = strtotime("+1 day", $date))
{
$custom_day = date("Y-m-d", $date);
$custom_third_sat[] = date('Y-m-d', strtotime('third Saturday "'.$custom_day.'"'));
}
echo "<pre>";
print_r($custom_third_sat);
Where am I wrong?
Every Months contain only one "third saturday" , so no need to do more looping of days. Just try this Code Once.
$frmdate = "2015-06-05";
$todate = "2015-08-31";
$custom_third_sat=array();
for ($date = date("Y-m-01", strtotime($frmdate)); $date <= $todate; $date = date("Y-m-01",strtotime($date."+1 Month"))) {
if($date>$todate){
break;
}
$t_date=date('Y-m-d', strtotime($date.' third Saturday'));
if($t_date>=$frmdate && $t_date<=$todate)
{
$custom_third_sat[] = $t_date;
}
}
echo "<pre>";print_r($custom_third_sat);
you should use of like third saturday of:try this
$custom_third_sat[] = date('Y-m-d', strtotime("third saturday of $custom_day"));
your full code can be something like this:
$frmdate = '2015-06-05';
$todate = '2015-08-31';
for ($date = strtotime($frmdate); $date <= strtotime($todate); $date = strtotime("+1 day", $date))
{
$custom_day = date("Y-m-d", $date);
if(!isset($custom_third_sat[date('Y-m-d', strtotime("third saturday of $custom_day"))])){
$custom_third_sat[date('Y-m-d', strtotime("third saturday of $custom_day"))] = date('Y-m-d', strtotime("third saturday of $custom_day"));
}
}
echo "<pre>";
print_r($custom_third_sat);
You are just missing the quotes to dates
<?php
$frmdate = '2015-06-05';
$todate = '2015-08-31';
for ($date = strtotime($frmdate); $date <= strtotime($todate); $date = strtotime("+1 day", $date))
{
echo"assa";
$custom_day = date("Y-m-d", $date);
$custom_third_sat[] = date('Y-m-d', strtotime('third Saturday "'.$custom_day.'"'));
}
echo "<pre>";
print_r($custom_third_sat);
?>

PHP to calculate latest 31 March

i want to calculate latest 31-Mar .... suppose date is 1-Jan-2012 i want result as 31-mar-2011 and if is 1-April-2011 then also i want result 31-mar-2011 and if its 1-mar-2011 it should come as 31-mar-2010.....hope i made my self clear ...(with php) ... i al calculating date with this for financial year ...
always between 31-mar-lastyear to 1-April-thisyear
... year should be taken automatically ...
i was trying like this
31-mar-date('y') and 31-mar-date('y')-1
but its not working as its taking current year every time.
Here is an example using the wonderful strtotime function of php.
<?php
$day = 1;
$month = 1;
$year = 2011;
$date = mktime(12, 0, 0, $month, $day, $year);
$targetMonth = 3;
$difference = $month - $targetMonth;
if($difference < 0) {
$difference += 12;
}
$sameDateInMarch = strtotime("- " . $difference . " months", $date);
echo "Entered date: " . date("d M Y", $date) . "<br />";
echo "Last 31 march: " . date("t M Y", $sameDateInMarch);
// the parameter 't' displays the last day of the month
?>
Something like this:
function getLast() {
$currentYear = date('Y');
// Check if it happened this year, AND it's not in the future.
$today = new DateTime();
if (checkdate(3, 31, $currentYear) && $today->getTimestamp() > mktime(0, 0, 0, 3, 31, $currentYear)) {
return $currentYear;
}
while (--$currentYear) {
if (checkdate(3, 31, $currentYear)) {
return $currentYear;
}
}
return false;
}
var_dump(getLast());
It should return the year or false.
if (date('m')>3) {
$year = date('Y').'-'.(date('Y')+1);
} else {
$year = (date('Y')-1).'-'.date('Y');
}
echo $year;
this is to get the current financial year for India

Categories