comparing dates in php - php

In the following php code, I am trying to show only those products from products.xml file that are stored in the last month. But my code does not work. Please help me in getting correct output. I also need to show products that are stored in the last 24 hours and last week.
$current_month = date("m");
$last_month = date('m', strtotime(date('-m')." -1 month"));
$xml = simplexml_load_file("products.xml");
$products = array();
foreach ($xml->product as $product) {
if ($product->date('m') == $last_month) {
$products[] = array( 'name' => (string)$product->name,
'details' => (string)$video->details );
}
}

Strtotime is nicer than you might think. For instance, this code;
if (date('m') > date('m', strtotime('last month')))
echo true;
else
echo false;
Will currently output "true" - because last month is 09, and this month is 10.
But what if this month is 01, and last month is 12? Then it would be false. I'd recommend you compare on years as well.
Edit: If this isn't a problem, and you only want to evaluate this for the most recent additions, then that should be fine. But you'll run into problems the year after if you only compare from last month, unless your import data only contains stuff from this year.

try
$last_month = date('m', strtotime("-1 month"));
$xml = simplexml_load_file("products.xml");
$products = array();
foreach ($xml->product as $product)
{
if ($product->date('m') == $last_month)
{
$products[] = array(
'name'=>(string)$product->name,
'details'=>(string)$video->details,
);
}
}

Related

Skip a value in do-while loop

I've got a script that sets up a array of dates which form a dropdown. The array is set up by some variables about the current date and an fixed offset for the last date (two weeks). Stripped down this is what it looks like:
public function getDatesOptionArray()
{
$datesArray = array();
$displayDate = Mage::getModel('core/locale')->storeDate();
$displayDate->add($this->_startDaysOffset, Zend_Date::DAY);
$dayOffset = $this->_startDaysOffset;
do
{
$dayofweek = date('w', strtotime($displayDate->toString(Varien_Date::DATE_INTERNAL_FORMAT)));
$datesArray[$displayDate->toString(Varien_Date::DATE_INTERNAL_FORMAT)] = Mage::helper('core')->formatDate($displayDate, Mage_Core_Model_Locale::FORMAT_TYPE_FULL);
$displayDate->add('1', Zend_Date::DAY);
$dayOffset++;
} while ($dayOffset <= $this->_endDaysOffset);
return $datesArray;
}
The thing is I want to leave out all the 'Sunday' options, and I've got the $dayofweek variable for each, where sunday is 0. I've tried to wrap the whole thing inside the do function in an if-statement (if $dayofweek !== 0), set an if ($dayofweek == 0) { continue;} and every other trick I could think of, but I get only either of these results
1: Only the first date is shown
2: All dates until the first sunday are shown, none after that
3: All dates are shown
I think I might be missing the point on the do-while loop; how do I exclude if $dayofweek == 0?
For me is something like this, i use while because Do...While(...) the first time it will not check your condition you'll enter your loop at last 1 time, and when you use while(...){} every time your program will check your condition
public function getDatesOptionArray()
{
$datesArray = array();
$displayDate = Mage::getModel('core/locale')->storeDate();
$displayDate->add($this->_startDaysOffset, Zend_Date::DAY);
$dayOffset = $this->_startDaysOffset;
while ($dayOffset <= $this->_endDaysOffset)
{
$dayofweek = date('w', strtotime($displayDate->toString(Varien_Date::DATE_INTERNAL_FORMAT)));
if ($dayofweek != 0) {
$datesArray[$displayDate->toString(Varien_Date::DATE_INTERNAL_FORMAT)] = Mage::helper('core')->formatDate($displayDate, Mage_Core_Model_Locale::FORMAT_TYPE_FULL);
}
$displayDate->add('1', Zend_Date::DAY);
$dayOffset++;
}
return $datesArray;
}
Let say the array is
$date = array(
2017-10-12,
2017-10-13,
2017-10-14,
2017-10-15,
2017-10-16,
2017-10-17,
2017-10-18,
2017-10-19,
2017-10-20,
2017-10-21,
2017-10-22,
2017-10-23,
2017-10-24,
2017-10-25
);
Now do this for remove sunday's dates
$i=0;
do{
if(date('w',strtotime($date[$i]))>0) $dateArray[] = $date[$i];
$i++;
} while ($i<count($date));
echo "<pre>";print_r($dateArray);
return $datesArray;
$dateArray will give you dates without sundays.

Am not able to check if month == equal datetime

I am trying to show results of each month.
Im having this for loop:
foreach ($overview as $day) {
$year = date("Y") - 1;
if ($day->user == $info->id) {
$startDate = new DateTime($day->Calendar_startdate);
$endDate = new DateTime($day->Calendar_enddate);
$s = $startDate->format('Y-m-d');
$e = $endDate->format('Y-m-d');
if ($s > $year) {
$workdays = number_of_working_days($s, $e);
$daysleft = $daysleft + $workdays;
} else {
}
}
}
This for loop is also in an if statement which echos the months.
Now I need to let it work for the months January, February etc...
I am able to not show results if in the previous year which works well.
If you want to compare $s with $year just change $year to :
$time = new DateTime('now');
/*** you can use `now` for today
/* or you can change to a fixed date exmp: 2016-01-01
*/
$year = $time->modify('-1 year')->format('Y-m-d');
Than you can compare $s > $year
I fixed by checking each month if it contained for example -01-
DB::table('Calendar')->where('Calendar_startdate', 'like','%' . $monthnumber . '%')->where('user', $info->id)->where('Calendar_type',2)->get();

PHP days difference calculation error

I have some PHP code to calculate the number of days between two specific dates. The difference should not count Sundays and Saturdays. Also, I have an array of dates, which includes holidays, which also need to be skipped.
I gave the starting date as 01-05-2015 and ending date as 01-06-2015. I gave the entire days in the month of may as array. Thus the difference should be 1 day. But I am getting the output as 7. What is the problem? Here is the code.
function dateRange($first, $last) {
$dates = array();
$current = strtotime($first);
$now = $current;
$last = strtotime($last);
while( $current <= $last ) {
if (date('w', $current) != 0){
$dates[] = date('d-m-Y', $current);
}
$current = strtotime('+1 day', $current);
}
unset($dates[0]);
return $dates;
}
$datea = "01-05-2015";
$date = "01-06-2015";
$hdsarray = array("1-05-2015","2-05-2015","4-05-2015","5-05-2015","7-05-2015","8-05-2015","9-05-2015","11-05-2015","12-05-2015","14-05-2015","15-05-2015","16-05-2015","18-05-2015","19-05-2015","21-05-2015","22-05-2015","23-05-2015","25-05-2015","26-05-2015","28-05-2015","29-05-2015","30-05-2015");
$datesarray = dateRange($datea, $date);
$result = array_diff($hdsarray,$datesarray);
$date_diff = sizeof($result);
echo $date_diff;
The only problem I can see is in the usage of array_diff, It actually includes the sat and sun which is excluded by dateRange function, if not found in holidays list.
Instead, you can pass your holiday dates in dateRange function, and filter over there.
function dateRange($first, $last, $excludeDates) {
$dates = array();
$current = strtotime($first);
$now = $current;
$last = strtotime($last);
while( $current <= $last ) {
if (date('w', $current) != 0 && date('w', $current) != 6 && !in_array(date('j-m-Y', $current), $excludeDates)){
$dates[] = date('d-m-Y', $current);
}
$current = strtotime('+1 day', $current);
}
return $dates;
}
$datea = "01-05-2015";
$date = "01-06-2015";
$hdsarray = array("1-05-2015","2-05-2015","4-05-2015","5-05-2015","7-05-2015","8-05-2015","9-05-2015","11-05-2015","12-05-2015","14-05-2015","15-05-2015","16-05-2015","18-05-2015","19-05-2015","21-05-2015","22-05-2015","23-05-2015","25-05-2015","26-05-2015","28-05-2015","29-05-2015","30-05-2015");
$datesarray = dateRange($datea, $date, $hdsarray);print_r($datesarray);
Result:
Array
(
[0] => 06-05-2015
[1] => 13-05-2015
[2] => 20-05-2015
[3] => 27-05-2015
[4] => 01-06-2015
)
All the 5 dates come in the result, are not sat, sun, and also not there in holidays list.
It seems that there are several problems here. First, as pointed out by others the condition:
if (date('w', $current) != 0){
only checks for Sundays, if it should also include Saturday's it should be:
if (date('w', $current) != 0 && date('w', $current) != 6){
Secondly, it seems that the $hdsarray array does not contain all of the days in May. It seems that all of the Wednesdays are missing.
The third issue is that you are using array_diff on two arrays, one containing Dates and the other ones containing Strings. From the documentation:
Two elements are considered equal if and only if (string) $elem1 ===
(string) $elem2. In words: when the string representation is the same.
In your $hdsarray you are using "1-05-2015" to denote the first day of the month, while:
echo date('d-m-Y', strtotime("1-05-2015"));
results in "01-05-2015". You will need to add an additional 0 in $hdsarray for these dates or work with dates as well.
Last but not least, the current algorithm will not work correctly if the $hdsarray contains dates for a Saturday or Sunday, the result of array_diff will still contain these dates. Since you want to filter the result of daterange the array_filter function might be more suitable.
Despite an answer has already been provided, here is a little snippet with a class handling everything for you:
<?php
class dateRange {
protected $start, $end, $daysToExclude, $datesToExclude;
function __construct($dateStart, $dateEnd, $daysToExclude, $datesToExclude) {
$this->start = $dateStart;
$this->end = $dateEnd;
$this->daysToExclude = $daysToExclude;
$this->datesToExclude = $this->fixFormat($datesToExclude);
}
public function getRangeLength ($callback = null) {
$tmp = array();
$now = strtotime($this->start);
$to = strtotime($this->end);
while ( $now <= $to ) {
if (!in_array(date("w", $now), $this->daysToExclude)) {
$tmp[] = date('d-m-Y', $now);
}
$now = strtotime('+1 day', $now);
}
is_callable($callback) && call_user_func($callback, array_diff($tmp,$this->datesToExclude));
return count(array_diff($tmp,$this->datesToExclude));
}
private function fixFormat($el) {
if (!is_array($el)) {
return false;
}
else {
foreach ($el as &$value) {
$value = date("d-m-Y",strtotime($value));
}
return $el;
}
}
}
?>
I decided to keep your current logic (using date_diff), but I thought that, in the future, you may have your boss telling you "You know what? I don't want to have mondays aswell there" so, with the current system, you will have to edit your function manually and, perhaps, you won't remember anymore what you did.
The class above expects four parameters:
dateStart (d-m-Y format)
dateEnd (d-m-Y format)
daysToExclude (array with IDs of the days to exclude -> example array(0,6) to exclude saturdays and sundays).
datesToExclude (array with the dates to exclude, every format supported).
The class will automatically fix the datesToExclude array format in order to allow you to use date_diff.
Here is an example to use it, following your case:
<?php
$dateStart = "01-05-2015";
$dateEnd = "01-06-2015";
$daysToExclude = array(0,6);
$exclusions = array(
"1-05-2015",
"2-05-2015",
"4-05-2015",
"5-05-2015",
"7-05-2015",
"8-05-2015",
"9-05-2015",
"11-05-2015",
"12-05-2015",
"14-05-2015",
"15-05-2015",
"16-05-2015",
"18-05-2015",
"19-05-2015",
"21-05-2015",
"22-05-2015",
"23-05-2015",
"25-05-2015",
"26-05-2015",
"28-05-2015",
"29-05-2015",
"30-05-2015"
);
$dateRange = new dateRange($dateStart, $dateEnd, $daysToExclude, $exclusions);
echo $dateRange->getRangeLength();
?>
The code above outputs 5.
The function getRangeLength also accepts a callback and will return the array resulting of the date_diff operation, so you can also:
$dateRange->getRangeLength(function($res) {
echo "Literal output: <br />";
print_r($res);
echo "<br />count is: " . count($res);
});
The above outputs:
Literal output:
Array ( [3] => 06-05-2015 [8] => 13-05-2015 [13] => 20-05-2015 [18] => 27-05-2015 [21] => 01-06-2015 )
count is: 5
So if you later will need to remove mondays too, you will be able to easily do that by changing daysToExclude to array(0,1,6);
Hope this will be helpful to anyone else who will need this, despite a valid answer has already been posted.
Your original problem, in any case, was pretty much related to the array_diff function, which was NOT doing its job because of the fact that the date strings were not compatible, because "1-01-2015" is different from "01-01-2015", unless you first convert BOTH of them to times and then back to dates.
The code is fine (except that $nowis not used at all). The problem is the $hdsarray is wrong:
It should $hdsarray = array("01-05-2015", "02-05-2015", "04-05-2015", "05-05-2015", "07-05-2015", "08-05-2015", "09-05-2015",...);
date('d-m-Y', $current);will always return a leading 0 for all days between 1 and 9.
That's where the difference comes from.

Only show html on certain days w/php

I only want to show some html on certain days of the week. I think I am very close, but cannot get this to work. Thanks for the help.
<?php
$dayofweek = date('l');
$daystoshow = array('Thursday','Sunday','Wednesday');
if ($dayofweek == $daystoshow) {
echo "show this";
}
?>
Use in_array() to check to see if a value in in an array:
if (in_array($dayofweek, $daystoshow)) {
Allright:
Lets use PHP date function
Do you want to show it only during a particular month ?
$date = date("m");
if ($date == "01") { // only on january
//output
}
Do you want to show it only during a particular day ?
$date = date("d");
if ($date == "01") { //Only on the first of the month
//output
}
Do you want to show it only during particular dayS ?
$days = array("01","11","28");
$date = date("d");
if (in_array($date,$days)) { //Only 01,11,28
//output
}
Do you want to show it only during particular days of week ?
$days = array("Thursday","Sunday","Wednesday");;
$date = date("l");
if (in_array($date,$days)) {
//output
}
Do you want to show it only during a particular year ?
$date = date("Y");
if ($date == "2014") { //Only on 2014
//output
}

Compare Dates PHP

I want to only shows result for the current month, but I have no idea how to do this, my current output is like this.
Output
2014-04-11
-> array
2014-04-11
2014-04-05
2014-03-29
PHP
$date = date('Y-m-d');
echo $date;
echo "<pre>";
foreach ($submissions as $test){
if($date >= substr($test['thing']['created'], 0, 10)){
echo substr($test['thing']['created'], 0, 10);
echo "<br>";
}
}
echo "</pre>";
My current code wont work as its only checking if the whole number is greater or equal to, any ideas anyone?
Just try with strtotime:
$year = date('Y');
$month = date('m');
foreach ($submissions as $test) {
$timestamp = strtotime($test['thing']['created']);
$testYear = date('Y', $timestamp);
$testMonth = date('m', $timestamp);
if (($month >= $testMonth && $year == $testYear) || $year > $testYear) {
// test passed
}
}
If your problem is to have only results of current month :
$date = date('Y-m');
echo "<pre>";
foreach ($submissions as $test){
// if month & year is equal
if($date == substr($test['thing']['created'], 0, 7)){
echo substr($test['thing']['created'], 0, 10);
echo "<br>";
}
}
echo "</pre>";
If you want to sort it, you will have to convert to timestamp
i'm not a pro in php but take a look here : http://fr2.php.net/manual/fr/function.date.php
does date('m') would be a solution for your problem?
You can try 2 ways :
convert them to timestamp, then compare the int
If you are taking the dates frome a DB, ORDER BY date in the query
Variable for current month first $cur_m=date('m')
Explode your variable in loop with -.
$p = explode('-',$test['thing']['created']);
in loop check for current month like below
if($p[1]==$cur_m){ your code... }

Categories