Listing timestamp month/year as blog archive in PHP - php

Assuming I have multiple timestamps of multiple years and months in an array of timestamps (eg 123456, 111222333, 2112321321, 232234422, 1111343222, 231111211, etc), I want to sort them into this format:
2012
06
09
2004
03
08
2003
01
02
Is there any way of doing this? I am using PHP

You can do this.
See if this gets you started; it's incomplete but takes care of most of it. Just a few additions and it should work how you want.
<?php
$timestamps = array();
for ($i = 0; $i < 100; ++$i) {
$ts = mktime(rand(0, 23), rand(0, 59), rand(0, 59), rand(1, 12), rand(1, 31), rand(2000, 2012));
$timestamps[] = $ts;
}
sort($timestamps);
$lastYear = null;
echo "<ul>\n";
foreach($timestamps as $ts) {
$year = date('Y', $ts);
if ($year != $lastYear) {
if ($lastYear != null) {
echo "</ul>\n";
}
$lastYear = $year;
echo "<li>$year<ul>\n";
}
echo "<li>" . date('m-d', $ts) . "</li>\n";
}
echo "</ul></ul>";
I create an array of 100 random timestamps to populate the list at the beginning.

I've found a solution:
foreach($timestamps as $time){
$year = date('Y', $time);
$month = date('m', $time);
if(!$ts_arr[$year]){
$ts_arr[$year] = array();
}
array_push($ts_arr[$year], $month);
$ts_arr[$year] = array_unique($ts_arr[$year]);
}
It's not perfect, but it works!

Related

Custom Month and Year inside php for-loop

I saw this question:
how to get the previous 3 months in php
My question is.. How do i output from a custom month.
I want to start from Mar 2018 (or any M Y user inputs) and it should output the next 3 (or any number user inputs) months.
Ex: Mar, Apr, May
The code below is from current month and year.
// current month: Aug 2018
for ($i = 0; $i <= 2; $i++){
$x = strtotime("$i month");
echo $dte = date('M Y', $x);
echo '<br>';
}
And the output is
Aug 2018
Sep 2018
Oct 2018
You could use the DateTime class and increment using a DateInterval object:
// Assuming these are the user inputs
$month = 11;
$year = 2015;
// We create a new object with year and month format
$date = DateTime::createFromFormat('Y m', $year . ' ' . $month);
for ($i = 0; $i <= 2; $i++){
// Output the month and year
echo $date->format('m Y') . '<br>';
// Add 1 month to the date
$date->add(new DateInterval('P1M'));
}
Output:
11 2015
12 2015
01 2016
Documentation:
DateTime::createFromFormat
DateTime::format
DateTime::add
Change it to this as below it will give you as expected see the below code
// current month: Aug 2018
$effective_date = "MAR 2018";
for ($i = 0; $i <= 2; $i++){
$x = strtotime("$i month",strtotime($effective_date));
echo $dte = date('M Y', $x);
echo '<br>';
}
This may be also helpful:
<?php
$month = 11;
$year = 2017;
$count = 15;
for ($i = 1; $i <= $count; $i++) {
$month++;
if ($month > 12) {
$month = 1;
$year++;
}
$x = DateTime::createFromFormat('Y-m', $year.'-'.$month);
echo $x->format('m-Y');
echo '<br>';
}
?>
Output:
12-2017
01-2018
02-2018
03-2018
04-2018
05-2018
06-2018
07-2018
08-2018
09-2018
10-2018
11-2018
12-2018
01-2019
02-2019
Try this code for add nth Days, Months and Years
$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>';
}
You can generate the date with strtotime() function
Check this phpfiddle
<?php
$currMonth = 11;
$currYear = 2017;
$count = 15;
$currentYear = date('M Y',strtotime($currYear.'-'.$currMonth));
echo $currentYear.'<br>';
for ($i = 1; $i < $count; $i++) {
$currMonth++;
if ($currMonth > 12) {
$currMonth = 1;
$currYear++;
}
$newMonthandYear = date('M Y',strtotime($currYear.'-'.$currMonth));
echo $newMonthandYear.'<br>';
}
?>
<?php
$year = date('Y');
//start at march
$startMonth = 7;
//go forwards 2 months
$stepForwards = 22;
for ($i = $startMonth; $i <= $stepForwards; $i++){
if($i > 12 ) {
$month = $i % 12 == 0 ? 12 : $i % 12;
}
else {
$month = $i;
}
echo date("M Y", strtotime(date($year.'-'.$month.'-1'))) . "<br/>";
if($month == 12) {
$year++;
echo "<br/>";
}
}

Counting the (year)quarters between two dates

I have project built using laravel and a I have to build a function that counts all the complete quarters that are in the selected date range - the dates used are inserted via input.
Here are the quarters(i used numerical representations for the months)
01 - 03 first quarter
04 - 06 second quarter
07 - 09 third quarter
10 - 12 forth quarter
I would really appreciate your help,because I've been at it for an entire day now and basically have nothing to show for it,i thing I've been trying so hard i'm actually at the point where i'm so tired, i can t think straight.
I do have some code but it;s worthless, because it doesn't work, and any kind of idea or snippet of code is welcomed.
Thanks for your help in advance.
I managed to do this using multiple functions; basically, if this is needed for chart statistics, then a more specific approach might be the case.
I have done this in Laravel with timestamp dates as input (this code can be adapted for getting semesters also :) , it works and is already tested):
public static function getQuartersBetween($start_ts, $end_ts)
{
$quarters = [];
$months_per_year = [];
$years = self::getYearsBetween($start_ts, $end_ts);
$months = self::getMonthsBetween($start_ts, $end_ts);
foreach ($years as $year) {
foreach ($months as $month) {
if ($year->format('Y') == $month->format('Y')) {
$months_per_year[$year->format('Y')][] = $month;
}
}
}
foreach ($months_per_year as $year => $months) {
$january = new Date('01-01-' . $year);
$march = new Date('01-03-' . $year);
$april = new Date('01-04-' . $year);
$june = new Date('01-06-' . $year);
$july = new Date('01-07-' . $year);
$september = new Date('01-09-' . $year);
$october = new Date('01-10-' . $year);
$december = new Date('01-12-' . $year);
if (in_array($january, $months) && in_array($march, $months)) {
$quarter_per_year['label'] = 'T1 / ' . $year;
$quarter_per_year['start_day'] = $january->startOfMonth();
$quarter_per_year['end_day'] = $march->endOfMonth()->endOfDay();
array_push($quarters, $quarter_per_year);
}
if (in_array($april, $months) && in_array($june, $months)) {
$quarter_per_year['label'] = 'T2 / ' . $year;
$quarter_per_year['start_day'] = $april->startOfMonth();
$quarter_per_year['end_day'] = $june->endOfMonth()->endOfDay();
array_push($quarters, $quarter_per_year);
}
if (in_array($july, $months) && in_array($september, $months)) {
$quarter_per_year['label'] = 'T3 / ' . $year;
$quarter_per_year['start_day'] = $july->startOfMonth();
$quarter_per_year['end_day'] = $september->endOfMonth()->endOfDay();
array_push($quarters, $quarter_per_year);
}
if (in_array($october, $months) && in_array($december, $months)) {
$quarter_per_year['label'] = 'T4 / ' . $year;
$quarter_per_year['start_day'] = $october->startOfMonth();
$quarter_per_year['end_day'] = $december->endOfMonth()->endOfDay();
array_push($quarters, $quarter_per_year);
}
}
return $quarters;
}
and getting the years between:
public static function getYearsBetween($start_ts, $end_ts, $full_period = false)
{
$return_data = [];
$current = mktime(0, 0, 0, date('m', $start_ts), date('d', $start_ts), date('Y', $start_ts));
while ($current < $end_ts) {
$temp_date = $current;
$year = new Date($temp_date);
$return_data[] = $year;
$current = strtotime("+1 year", $current); // add a year
}
if ($full_period) {
$return_data[] = $end_ts;
}
return $return_data;
}
, also getting the months needed
public static function getMonthsBetween($start_ts, $end_ts, $full_period = false)
{
$return_data = $month_list = [];
$current = mktime(0, 0, 0, date('m', $start_ts), date('d', $start_ts), date('Y', $start_ts));
while ($current <= $end_ts) {
$temp_date = $current;
$date = new Date($temp_date);
$month_list[] = $date;
$current = strtotime("+1 month", $current); // add a month
}
$start_date_last_month = new Date(array_first($month_list));
$start_date_last_month = $start_date_last_month->startOfMonth()->format('m-d');
$temp_end_date = new Date($start_ts);
$temp_end_date = $temp_end_date->format('m-d');
if ($start_date_last_month < $temp_end_date) {
array_shift($month_list);
}
$end_date_last_month = new Date(end($month_list));
$current_day_month = $end_date_last_month->endOfMonth()->format('m-d');
$temp_end_date = new Date($end_ts);
$end_day_of_month = $temp_end_date->format('m-d');
if ($end_day_of_month < $current_day_month) {
array_pop($month_list);
}
if (count($month_list) == 0) {
$month_list[] = $end_date_last_month->subMonth();
}
$return_data = $month_list;
if ($full_period) {
$return_data[] = $end_ts;
}
return $return_data;
}
You can do something like in this example:
$February = 2;
$October = 10;
$completedQuarters = ceil($October/3) - ceil($February/3); // = 3
What about the quarter in which the date range starts, should it also count? If it should only count if it begins in the first month of a quarter you can check for it like this:
$completedQuarters = ceil($October/3) - ceil($February/3) -1; // = 2
if($February-1%3 == 0) $completedQuarters += 1;
You´re description is not very clear, let me know if that´s what you had in mind.
Not sure if the following is what you are meaning but might be useful
$date_start='2015/03/12';
$date_end='2017/11/14';
$timezone=new DateTimeZone('Europe/London');
$start=new DateTime( $date_start, $timezone );
$end=new DateTime( $date_end, $timezone );
$difference = $end->diff( $start );
$months = ( ( $difference->format('%y') * 12 ) + $difference->format('%m') );
$quarters = intval( $months / 3 );
printf( 'Quarters between %s and %s is %d covering %d months', $start->format('l, jS F Y'), $end->format('l, jS F Y'), $quarters, $months );
/*
This will output
----------------
Quarters between Thursday, 12th March 2015 and Tuesday, 14th November 2017 is 10 covering 32 months
*/
Something like this in the function and you should be set.
use Carbon\Carbon;
$first = Carbon::parse('2012-1-1'); //first param
$second = Carbon::parse('2014-9-15'); //second param
$fY = $first->year; //2012
$fQ = $first->quarter; //1
$sY = $second->year; //2014
$sQ = $second->quarter; //3
$n = 0; //the number of quarters we have counted
$i = 0; //an iterator we will use to determine if we are in the first year
for ($y=$fY; $y < $sY; $y++, $i++) { //for each year less than the second year (if any)
$s = ($i > 0) ? 1 : $fQ; //determine the starting quarter
for ($q=$s; $q <= 4; $q++) { //for each quarter
$n++; //count it
}
}
if ($sY > $fY) { //if both dates are not in the same year
$n = $n + $sQ; //total is the number of quarters we've counted plus the second quarter value
} else {
for ($q=$fQ; $q <= $sQ; $q++) { //for each quarter between the first quarter and second
$n++; //count it
}
}
print $n; //the value to return (11)

PHP Get the year of most recent occurrance of specific date

I am working on a script that will determine when a specific calendar date most recently occurred.
This post, Get the year of a specified month in previous 12 months?, is the basis of my current beta. It was written for a monthly result and not a specific date.
<?php
if (empty($_GET['m'])) {
$m = "October";
} else {
$m = htmlspecialchars($_GET['m']);
}
if (empty($_GET['d'])) {
$d = "1";
} else {
$d = htmlspecialchars($_GET['d']);
}
date_default_timezone_set('America/Los_Angeles');
$m = date('m', strtotime($m));
$c = (mktime(0,0,0,$m,$d) < time())
? mktime(0,0,0,$m,$d)
: mktime(0,0,0,$m,$d,date("Y") -1);
$from = date('F jS', $c) . " last occurred in " . date('Y', $c) . ".";
echo $from;
?>
The result of the default value, October 1 is:
"October 1st last occurred in 2012."
For June 11th, as a random example:
"June 11th last occurred in 2013."
All date results are TRUE, except for the result for February 29th:
"March 1st last occurred in 2013."
Obviously, this is a false statement since the desired result is:
"February 29th last occurred in 2012."
I'm kind of stuck, what is the best way to add a true leap year result?
This is calculating last true year. Replace with following codes.
<?php
if (empty($_GET['m'])) {
$m = "October";
} else {
$m = htmlspecialchars($_GET['m']);
}
if (empty($_GET['d'])) {
$d = "1";
} else {
$d = htmlspecialchars($_GET['d']);
}
date_default_timezone_set('America/Los_Angeles');
$y = date('Y');
if($m == "February" && $d == "29") $y = $y - ($y % 4);
$m = date('m', strtotime($m));
$c = (mktime(0,0,0,$m,$d) < time()) ? mktime(0,0,0,$m,$d,$y) : mktime(0,0,0,$m,$d,$y);
$from = date('F jS', $c) . " last occurred in " . $y . ".";
echo $from;
?>
Results
For 2013: Result 2012
For 2012: Result 2012
For 2011: Result 2008
For 2010: Result 2008
$month = 9;
$day = 1;
$timestamp = mktime(0, 0, 0, $month, $day);
if ($timestamp > time()) {
$timestamp = mktime(0, 0, 0, $month, $day, date('Y') - 1);
}
covert timestamp to your desire format.

displaying the dates in a particular format php

I have a date array sorted in asc order. I want to display the date as
Oct 10,12,24 2012
Dec 12,20,24 2012
Jan 02,10,25 2013
I have got the dates as the month ie.Oct,Dec,Jan.. and the dates and year, but i want it to be displayed in the above mentioned format. I have tried the below code, but it is not giving the desired result. Can someone pls help me with this?
$CruiseDetailsSailing is the array containing the date in an ascending order.
if (count($CruiseDetailsSailing) > 0) {
$date = array();
$month = array();
$Year = array();
for ($n = 0; $n < count($CruiseDetailsSailing); $n++) {
if ($CruiseDetailsSailing[$n] != "") {
$date[] = date('Y-m-d', strtotime($CruiseDetailsSailing[$n]));
}
}
}
sort($date);
if (count($date) > 0) {
$temp = "";
$yeartemp = "";
for ($p = 0; $p < count($date); $p++) {
$month = date("M", strtotime($date[$p]));
$day = date("d", strtotime($date[$p]));
$year = date("Y", strtotime($date[$p]));
if ($month != $temp) {
$temp = $month;
?>
<li> <?php
echo $temp . " " . $day . ", ";
} else {
echo $day . ", ";
}
if (($p != 0) && ((date("M", strtotime($date[$p]))) == (date("M", strtotime($date[$p - 1])))) && ((date("Y", strtotime($date[$p]))) == (date("Y", strtotime($date[$p - 1]))))) {
echo $year;
}
if (($p != 0) && ((date("M", strtotime($date[$p]))) != (date("M", strtotime($date[$p - 1])))) && ((date("Y", strtotime($date[$p]))) != (date("Y", strtotime($date[$p - 1]))))) {
echo $year;
}
}
Oct is the month and 10,12,24 are the months and 2012 is the year. I got the the dates as Oct 10 2012,Oct 12 2012,Oct 24 2012. I just want to display the results as Oct only once and then the dates and the year just once.
Thanks,
this should do:
sort($date); // sorted input array containing dates
$result_dates = Array();
// bring dates in correct format
foreach($date as $current_date) {
$month = date("M", strtotime($current_date));
$day = date("d", strtotime($current_date));
$year = date("Y", strtotime($current_date));
$result_dates[$year][$month][] = $day;
}
// output dates
foreach($result_dates as $year => $months) {
foreach($months as $month => $days) {
echo $month . " " . implode(",", $days) . " " . $year . "\n";
}
}
the following input:
$date = Array('10/03/2012', '10/10/2012', '10/17/2012', '11/04/2012', '11/05/2012', '11/23/2012');
results in:
Oct 03,10,17 2012
Nov 04,05,23 2012
You can do it simply like this
/* Array to pass the function
$date_array = array(
'2012-10-10',
'2012-12-10',
'2012-24-10'
);
*/
function getMyDateFormat($date_array){
$days = array();
$year = '';
$month = '';
sort($date_array);
if(count($date_array)>0){
foreach($date_array as $row)
{
$days[] = date('d',strtotime($row));
$year = date('Y',strtotime($row));
$month = date('M',strtotime($row));
}
$new_date = $month .' '. implode(',',$days) .' '. $year;
return $new_date;
}
}

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