I have a number of variables that store a year, month and series of dates for that month (there are 2 of these for 2 separate months). I then need to incorporate these into what I believe is a multidimensional array (haven't worked with these types of arrays before). Here's my code that has the variables:
// Set the default timezone
date_default_timezone_set('Australia/Sydney');
$month1 = date('m');
$year1 = date('Y');
$dates1 = '3 5 6 10 12 13 17 19 20 24 26 27 31';
$month2 = date('m', strtotime('first day of next month')) ;
$year2 = date('Y', strtotime('first day of next month')) ;
$dates2 = '10 15 26';
Using Dec 10, 2013 as the current date and the above list of dates I then need to end up with an array in this format:
array("year" => array("month" => array(days)));
that would look like this:
$daysArray = array ("2013" => array("12" => array(3,5,6,10,12,13,17,19,20,24,26,27,31)), "2014" => array("1" => array(10,15,26)));
I'm not sure how to convert these 6 variables into a multidimensional array?
Considering a few edge cases as well (same year etc), i think this is a rather simple (readable) solution:
// Sample data
$month1 = 12;
$year1 = 2013;
$dates1 = '3 5 6 10 12 13 17 19 20 24 26 27 31';
$month2 = 1;
$year2 = 2014;
$dates2 = '10 15 26';
$result = combineDateArrays(createDateArray($year1, $month1, $dates1), createDateArray($year2, $month2, $dates2));
function createDateArray($year, $month, $dates) {
return array($year=>array($month=>explode(" ", $dates)));
}
function combineDateArrays($dateArray1, $dateArray2) {
foreach($dateArray2 as $year=>$months) {
foreach($months as $month=>$days) {
if (!isset($dateArray1[$year])) $dateArray1[$year] = array();
$dateArray1[$year][$month] = $days;
}
}
return $dateArray1;
}
You can create an array from a string using explode:
$daysArray = array($year1 => $month1 => explode(' ', $dates1), $year2 => $month2 => explode(' ', $dates2));
Related
This question already has answers here:
PHP Carbon, get all dates between date range?
(11 answers)
Closed 4 years ago.
Good day.
Ive been trying to get the days from the current day using Carbon in Laravel. So if today is the December 20 I want to get an array with:
December 20, 2018
December 21, 2018
December 22, 2018
December 23, 2018
December 24, 2018
I want to do it for 2 weeks or maybe even 3 weeks. This is what I got so far.
$currentdate = Carbon::now()->format('m/d/Y');
$ts = strtotime($currentdate);
$year = date('o', $ts);
$week = date('W', $ts);
$datearray = [];
for($i = 1; $i <= 7; $i++) {
$ts = strtotime($year.'W'.$week.$i);
array_push($datearray,date("m/d/Y", $ts));
}
The code above gives me for the week from the starting of the week and not from the day going forward.
If you are already using Carbon, use its power!
use \Carbon\Carbon;
// how many days you want in your array
$count = 7;
$dates = [];
$date = Carbon::now();
for ($i = 0; $i < $count; $i++) {
$dates[] = $date->addDay()->format('F d, Y');
}
// Show me what you got
print_r($dates);
Output is:
Array
(
[0] => December 22, 2018
[1] => December 23, 2018
[2] => December 24, 2018
[3] => December 25, 2018
[4] => December 26, 2018
[5] => December 27, 2018
[6] => December 28, 2018
)
Try this,
$datearray = [];
for($i = 0; $i < 7; $i++) {
array_push($datearray, date('F d, Y', strtotime($i == 0 ?'today UTC':'today +'.$i.'day')));
//push to array as 'December 20, 2018'
}
enjoy coding~! :)
I want an array of containing weeks of current month, How can i get this? I have tried different methods but none of them is working for me..
$month = date('m'); // it should be CURRENT MONTH Of Current Year
$year = date('y'); // Current year
$beg = (int) date('W', strtotime("$year-$month"));
$end = (int) date('W', strtotime("$year-$month"));
I have used the above code but not working..
I want to put those week numbers of current month into an array like
array ('1' => 'first week of march', '2' => '2nd week of march', '3' => '3rd week of march', '4' => '4th week of march', '5' => '5th week of march' ) etc
1,2,3,4,5 in array can be week number
For getting beginning and ending ISO week number use below code:
$beg = (int) date('W', strtotime(date("Y-m-01")));
$end = (int) date('W', strtotime(date("Y-m-t")));
function weeksOfMonth($month, $year){
$num_of_days = date("t", mktime(0,0,0,$month,1,$year));
$lastday = date("t", mktime(0, 0, 0, $month, 1, $year));
$no_of_weeks = 0;
$count_weeks = 0;
while($no_of_weeks < $lastday){
$no_of_weeks += 7;
$count_weeks++;
}
return $count_weeks;
}
echo weeksOfMonth(3, 2017);
After some hard time looking for it, Here is the Answer, Sorry for posting a bit late here. I hope it will help you guys.
public static function getWeeksOfMonth()
{
$currentYear = date('Y');
$currentMonth = date('m');
//Substitue year and month
$time = strtotime("$currentYear-$currentMonth-01");
//Got the first week number
$firstWeek = date("W", $time);
if ($currentMonth == 12)
$currentYear++;
else
$currentMonth++;
$time = strtotime("$currentYear-$currentMonth-01") - 86400;
$lastWeek = date("W", $time);
$weekArr = array();
$j = 1;
for ($i = $firstWeek; $i <= $lastWeek; $i++) {
$weekArr[$i] = 'week ' . $j;
$j++;
}
return $weekArr;
}
The Result will be the weeks of current Month..
Array (
[26] => week 1
[27] => week 2
[28] => week 3
[29] => week 4
[30] => week 5
[31] => week 6
)
I had a technical test and one of the things I had to do is a program that has an input of two dates, and has to output the months with 5 sundays between these two dates. A string $dates has the two dates in the same line
example: juny 2014 october 2014
I need to use these two dates to do stuff.
In this point, I was thinking to do two separate strings to work with each date, like this:
$arrayDates = split(" ",$dates);
Then:
$firstDate = $dates[0].$dates[1];
$secondDate = $dates[2].$dates[3];
But I see this way of doing things too obvious and not dynamyc. Somebody knows a better or more elegant/apropriate way to do this?
Edit: this is the full code
<?php
date_default_timezone_set('UTC');
//output month with five sundays
foreach(file($argv[1]) as $date){
$totalDays=prepareDateArray($date);
calculateSundays($totalDays,$date);
}
function prepareDateArray(&$date){
$regexPattern = "/([a-z]+ [0-9]{4})/i";
$matchCount = preg_match($regexPattern, $date, $matches);
if($matchCount == 0)return;
$date = preg_replace("# +#",' ',$date);
$date = split(' ',$date);
$totalDays = parseDate($date);
return $totalDays;
}
function parseDate(&$date){
$nIndex = count($date);
if($nIndex%2==0){
//Add first day of the month to first Date
$date[0] = '01-'.$date[0].'-'.$date[1];
//Get lastMonthDay
$lastMonthDay = date('t', strtotime($date[2].'-'.$date[3]));
//Add last day of the month to secondDate
$date[1] = $lastMonthDay.'-'.$date[2].'-'.$date[3];
//Calculates distance between dates in days
$firstDate = strtotime($date[0]);
$secondDate = strtotime($date[1]);
if($firstDate>$secondDate)exit('First date must be earlier than second date');
$datediff = $secondDate - $firstDate;
unset($date[2],$date[3]);
return $datediff/(60*60*24);
}else{
exit('Insert valid input');
}
}
function calculateSundays($totalDays,$tempDate){
$sundays=0;
$output=0;
for($day=1;$day<=$totalDays;$day++)
{
$dayOfWeek = date('w', strtotime($tempDate[0].' + '.$day.' days'));
if($dayOfWeek == 0)$sundays++;
if($sundays == 5){
$output++;
$sundays = 0;
}
}
if($output == 0)print("Wrong date \n");
else print($output."\n");
}
?>
You can create a simple regex for this operation can you check out the code below;
<?PHP
header('Content-Type: text/plain; charset=utf8');
$regexPattern = "/([a-z]+ [0-9]{4})/i"; //This will match a letters + space + 4 digit number together
$inputString = "juny 2014 october 2014 february 2016 march 2017 july 2010 FEBRUARY 2014";
$matchCount = preg_match_all($regexPattern, $inputString, $matches);
print_r($matches);
?>
You will get an output like that;
Array
(
[0] => Array
(
[0] => juny 2014
[1] => october 2014
[2] => february 2016
[3] => march 2017
[4] => july 2010
[5] => FEBRUARY 2014
)
[1] => Array
(
[0] => juny 2014
[1] => october 2014
[2] => february 2016
[3] => march 2017
[4] => july 2010
[5] => FEBRUARY 2014
)
)
And working example is here http://ideone.com/LuQqEN
i use same as cihan-uygun code but my Regx expression is little change
here is code
example :
I need dates output from these strings
2020 Ice Harbor All-Ages Master/Expert - Nov 21, 2020
2020 Ice Harbor Scholastic Open (Nov 21, 2020 - Nov 22, 2020)
<?php $regexPattern = "/[A-Z]{3} [0-9]{2}\, [0-9]{4}/i";
preg_match_all($regexPattern, $stringgosehere, $matches); ?>
Given the information below:
Year: 2012
Weeknumber: 4
Dayname: TUE
How can i convert this to a valid date like 2012-01-12 (YYYY-MM-DD) using PHP's date functions?
Thanx
The DateTime class can't do this, but the function strptime can.
$d = strptime('TUE 4 2012', '%a %W %Y');
var_dump($d);
That returns an array:
array
'tm_sec' => int 0
'tm_min' => int 0
'tm_hour' => int 0
'tm_mday' => int 24
'tm_mon' => int 0
'tm_year' => int 112
'tm_wday' => int 2
'tm_yday' => int 23
'unparsed' => string '' (length=0)
Note that tm_year contains the number of years since 1900 and tm_month is 0-based, not 1-based. So this does represent 2012-01-24, which is correct.
Use this function:
function get_date($year,$week,$day,$start_sunday=false){
$day_array = array('Mon'=>1,'Tue'=>2,'Wed'=>3,'Thu'=>4,'Fri'=>5,'Sat'=>6,'Sun'=>($start_sunday?0:7));
$month_array = array(31,($year%4==0?29:28),31,30,31,30,31,31,30,31,30,31);
$week *= 7;
$month = 1;
for($i=0;$i<count($month_array);$i++){
if($week-$month_array[$i]<=0){
break;
}
$week -= $month_array[$i];
$month++;
}
$format = "$year $month $week";
$date = date_create_from_format("Y m j",$format);
$date_num = date_format($date,"D");
$curr = $day_array[ucfirst(strtolower($day))]-$day_array[$date_num];
$got_date = strtotime("$curr ".($curr==1||$curr==-1?"day":"days"),strtotime(date_format($date,"Y-m-j")));
return $got_date;
}
where $start_sunday should be true if week starts from sunday
$year is the year
$week is week number
$day is short weekday name i.e.mon,tue,wed,....
this function will get you a date form the given format.
Enjoy............
I have a date in the following format
November 18, 2009, 3:00PM
How can i break that up so that i can store each value as its own variable?
such as...
$month //November
$day //18
$year //2009
$hour //03
$minute //00
$ampm //PM
Use the 'date_parse' (http://nl2.php.net/manual/en/function.date-parse.php) function. It returns an array with the parsed items:
Array
(
[year] => 2006
[month] => 12
[day] => 12
[hour] => 10
[minute] => 0
[second] => 0
[fraction] => 0.5
[warning_count] => 0
[warnings] => Array()
[error_count] => 0
[errors] => Array()
[is_localtime] =>
)
Convert your date into a timestamp, then with the timestamp you can easily get your parts. An other way is using a regular expression.
$str = "November 18, 2009, 3:00PM";
list($month,$day,$year,$time) = preg_split('/[ ,]/',$str,false,PREG_SPLIT_NO_EMPTY);
preg_match('/([0-9]+):([0-9]+)([AP]M)/',$time,$timeparts);
list($time,$hour,$minute,$ampm) = $timeparts;
echo "\$month $month\n";
echo "\$day $day\n";
echo "\$year $year\n";
echo "\$hour $hour\n";
echo "\$minute $minute\n";
echo "\$ampm $ampm\n";
Output
$month November
$day 18
$year 2009
$hour 3
$minute 00
$ampm PM
More complex solution.
If your dates may be in the different standards you can use date() function (http://php.net/manual/en/function.date.php) + strtotime() function (http://php.net/manual/en/function.strtotime.php), which parse string and returns the unix timestamp.
For example, if you want to get a year from your date string you could write next code:
$date = 'November 18, 2009, 3:00PM';
$year = date('Y', strtotime($date));
Or, if you want to know how much days in the month in date you get, you could write such code:
$date = 'November 18, 2009, 3:00PM';
$num_of_days = date('t', strtotime($date));
't' returns the number of days in the given month.