compare dates not working - php

Hallo,
I am comparing 2 dates. It is clear that $db_minus7 is greater so the value of $can_invoiced should be 'maybe' but it is 'Yes'. When i execute.
<?php
$db_minus7 = '2010-07-05 09:45:29.420';
$completion_date = '30.07.2009';
if(date("m-d-Y",strtotime($db_minus7)) > date("m-d-Y",strtotime($completion_date))) {
$can_invoiced = 'maybe';
} else {
$can_invoiced = 'Yes';
}
echo $can_invoiced;
?>
please help

why don't you just compare the times instad of formating them again like this:
if(strtotime($db_minus7) > strtotime($completion_date)) {
$can_invoiced = 'maybe';
} else {
$can_invoiced = 'Yes';
}
EDIT:
if you want to use date(), use "Ymd" or "Y-m-d" as pattern because it's string-comparision, and this is the logical order to work with (arrange the patterns from "big"(years) to small (days... or maybe seconds, if you need));

Dont' use "m-d-Y" but "Y-m-d".
01-01-2010 is lower than 02-01-2009 (bad !) but 2010-01-01 is not lower than 2009-01-02 (good !).

Compare the dates as datestamps, not as strings:
if(strtotime($db_minus7) > strtotime($completion_date)) {
If you have to compare the dates as strings, then use Y-m-d rather than m-d-y

Never Compare Dates as strings, even if it works for your Testcases it will fall on your feets sooner or later ... or maybe... richard stallman will hunt you down, i don't know ...
if(strtotime($db_minus7) > strtotime($completion_date)) {
$can_invoiced = 'maybe';
} else {
$can_invoiced = 'Yes';
}

Related

Removing Weekends From Array

I have a JSON of all bitcoin prices for previous 90 days. I'm trying to only work with the weekday prices, excluding weekend prices. This is how I am doing it. Could you please tell me what I'm doing wrong or point me in the right direction?
<?php
$string = file_get_contents("https://blockchain.info/charts/market-price?timespan=90days&format=json");
$btc_price = json_decode($string, true);
$allDays = $btc_price[values];
$weekends = array_filter($allDays[values][x], function($d) {
return (date('N', strtotime(date("Y-m-$d"))) >= 6);
});
$allDays[$year][$month] = array_diff($allDays[$year][$month], $weekends);
echo "<pre>";
print_r($allDays);
?>
You're fairly close. I've made a few changes to get it working:
Instead of passing in $allDays['values']['x'], you should pass in all of the days. This will allow you to remove each weekend day without having to do the array_diff step. $allDays['values']['x'] should be $allDays.
Your expression in the array_filter callable was wrong. I'm not clear what your intention was, but it looks like you were attempting to get the day of the week and filter on that. That's a good strategy, but your implementation wasn't effective. You can get the day of the week with w in date and pass in the unix timestamp you were given from the API. Also, checking for greater than 6 wasn't effective, since Sunday is 0.
$weekends = array_filter($allDays[values][x], function($d) {
return (date('N', strtotime(date("Y-m-$d"))) >= 6);
});
should be changed to:
$allDays = array_filter($allDays, function($d) {
return !(date('w', $d['x']) == 6 || date('w', $d['x']) == 0);
});
I've cleaned up some syntax. When accessing array keys, you should wrap your indexes in quotes. PHP was trying to interupt your keys as constants before falling back to the expected behavior. $allDays[values][x] should have been $allDays['values']['x'].
Here's the full snippet so you have context:
<?php
$string = file_get_contents("https://blockchain.info/charts/market-price?timespan=90days&format=json");
$btc_price = json_decode($string, true);
$allDays = $btc_price['values'];
$allDays = array_filter($allDays, function($d) {
return !(date('w', $d['x']) == 6 || date('w', $d['x']) == 0);
});
// This is just done to reset the keys in the array. It's entirely optional.
$allDays = array_values($allDays);
echo "<pre>";
print_r($allDays);
?>

show data only if currentmonth and currentyear are larger than

Let say currentmonth is 06 and currentyear 2017
i have dropdown of year and month ..
if i select year 2017 and month of July which is larger then currentmonth
how do i show there is not data available yet
my current code..and its not working..i'm a newbie and not sure im doing this right or not...
$mystartingyear=2017;
$mystartingmonth=01;
$currentmonth=date("m");
$currentyear=date("Y");
if ($currentyear >= $mystartingyear && $currentmonth >= $mystartingmonth)
{
echo "Show Data";
}
else
{
echo "No Data yet";
}
i also tried it like this
$mystartingyear=2017;
$mystartingmonth='01';
$currentmonth=12;
$currentyear=2017;
//$currentmonth=date("m");
//$currentyear=date("Y");
if ($currentyear >= $mystartingyear && $currentmonth >= $mystartingmonth)
{
echo "Show Data";
}
else
{
echo "No Data yet";
}
it always display "show data"
Edit:
Integers from 01 to 07 are ok just as long as you don't do 010 (with 3 integers) since that will be represented as 8. But as soon as you start hitting 08 and 09 for the months of August and September (which may be what's in your unknown dropdown), you will have problems.
So it's best you quote it.
Consult "Footnotes".
Original answer:
The leading zero in 01 for:
$mystartingmonth = 01;
^^
is treated as an octal.
It needs to be quoted:
$mystartingmonth = '01';
Octals references:
http://php.net/manual/en/language.types.integer.php
https://en.wikipedia.org/wiki/Octal
Footnotes:
If your current code is failing you, then something else is failing you.
You mention in your question that you're using this from a dropdown and that code wasn't included, nor how it's being passed.
Use PHP's error reporting, set to catch and display:
http://php.net/manual/en/function.error-reporting.php
Verify your conditional statement's logic also; both conditions must be met.
There is missing semicolon after first echo i.e. code should be
echo "Show Data";
Then every thing should work fine,
The date(); function in php returns the date in string and when you compare a string with integer it is implicitly converted into equivalent integer variable,if you want for sure you can use intvar(); function which converts variable to equivalent integer.But in your case it is not necessary.For more about i recommend you to read php manual .

How to compare date strings in the format yyyy-mm-dd in PHP

I have a range of dates in string format in the form of
'2014-10-12'
what i want to do is compare these dates so i can get the oldest and the youngest.
In PHP how do i convert these to a format where i can do the following?
$oldestdate;
$youngesdate;
//loop though all the dates
if($exampledate < $youngesdate)
$youesdate = $exampledate;
if($exampledate > $oldestdate)
$oldestdate = $exampledate;
Thanks
The nice thing about YYYY-MM-DD style dates is that they will always sort correctly, whether treated as text (as in your example), numbers (e.g. 20141012), or actual dates.
Thus, there's no need to do anything special to compare them as long as everything is the same format. Your code, as written, should work as-is (besides the typos for $youngestdate).
Note that if you want to do anything besides comparing them -- e.g. anything actually involving treating them like actual dates -- you will indeed want something like strtotime() or a mix of mktime() + substr()
have you tried strotime? reference http://php.net/manual/de/function.strtotime.php
then you can easily compare with <and > and so on.
have you tried checkdate(12, 31, 2000)? PHP.net Checkdate function
For years between 1 and 32767 inclusive.Check post 2 in the php.net link
You should use the DateTime class.
$arr = ['2012-10-12', '2004-10-12', '2014-08-12', '2014-09-12', '2014-09-13', '2014-09-11'];
$_now = new DateTime('now');
foreach ( $arr as $_t ) {
$d = new DateTime ( $_t );
if ( !isset($newest) || $d >= $newest ) $newest = $d;
if ( !isset($oldest ) || $d <= $oldest ) $oldest = $d;
}
echo 'Newest ' . $newest->format('Y-m-d');
echo 'Oldest' . $oldest->format('Y-m-d');
Take a look here: Reference on php.net
And here is an working example

time period in time period (PHP)

i try to find out if a Timeperiod is inside a timeperiod. I have my reference time period and my comparative time period.
Let me make an example:
Time period A (reference) goes from 1.1.2014 to 1.2.2014 (tt.mm.yyyy).
Time period B (comparative) goes from 1.4.2014 to 1.5.2014.
=> This would be totaly ok.
Time period C (reference) goes from 1.1.2014 to 1.3.2014
Time period D (comparative) goes from 1.2.2014 to 1.5.2014.
=> Not ok because D is in C.
I hope you get what i want. I tried to make serval < = > if actions but this starts to get to huge and slow. Maybe there is a faster ways to do so.
Also, is MySQL able to do such things?
you can try this with php timestamp
$reference_start_date = "1.1.2014";
$reference_end_date = "1.2.2014";
$comparative_start_date = "1.4.2014";
$comparative_end_date = "1.5.2014 ";
$reference_start_time = strtotime(str_replace(".", "-", $reference_start_date);
$reference_end_time = strtotime(str_replace(".", "-", $reference_end_date);
$comparative_start_time = strtotime(str_replace(".", "-", $comparative_start_date);
$comparative_end_time = strtotime(str_replace(".", "-", $comparative_end_date);
if($comparative_start_time>$reference_start_time && $comparative_start_time<$reference_end_time)
{
echo "Not OK";
}
else if($comparative_end_time>$reference_start_time && $comparative_end_time<$reference_end_time)
{
echo "Not OK";
}
else if($comparative_start_time<$reference_start_time && $comparative_end_time>$reference_end_time)
{
echo "Not OK";
}
else
{
echo "OK";
}
you can do like below:
Check Reference_start >= comparative_start && Reference_end < comparative_end, If this condition become true than your time will be overlapped.
If you have a reference period (having startDate and endDate) and you have a comparative period, then you can have this where clause in MySQL:
where ((reference.startDate > comparative.endDate) or reference.endDate < comparative.startDate)
which would be true if the two periods have no intersection.
Assuming you have your dates give in UTC it is really simple to compare two date ranges. There are 5 specific cases that could happen:
11111......
......22222
..11111.....
.....22222..
...11111....
...22222....
.....11111..
..22222.....
......11111
22222......
Only the first and the last one are the ones you are looking for. It's easy to construct an if query of it and negate it:
if (!($dateRange1End <= $dateRangeStart2 && $dateRange2End <= $dateRange1Start))
// NOT OKAY
else
// OKAY

PHP verify correct time format in $value

I have an online form that has a few fields with time data. I store this data into the MySQL data base into a time field, which needs a format hh:mm:ss. If the user inputs the time in this format correctly, then i want to accept the data. I also want to allow users to input the time in standard US time, like 9:30 am or 11:25 pm or 10:27 am etc.
Basically I want to test if the time is in the proper database format first (hh:mm:ss), then if it is not, test if it is in the second accepted format (hh:mm am/pm), and if it is, then I will use the PHP function strtotime() to convert it into the database time format. If it is in neither of these formats, then we display an error message and die.
Does anyone know how to test if the value of a variable matches one of these time formats?
Pseudo PHP code of what I want to do:
<?php
$value = //some time;
if (is_database_time($value)){
// good no problem
}else if (is_usa_time($value)){
$value = strtotime($value);
}else{
die("error incorrect time format, try again.");
}
?>
** EDIT **
Thanks everyone for the help. I used some of the info here to make a function that works perfectly:
<?php
function filter_time($key,$value){
// this section handles the storage of time data
if (preg_match('/^(0?\d|1\d|2[0-3]):[0-5]\d:[0-5]\d$/', $value)){
//do nothing
}else if (preg_match('/^(0?\d|1[0-2]):[0-5]\d\s(am|pm)$/i', $value)){
$value = date( 'H:i:s', strtotime($value));
}else{
display_error('incorrect time format in '.$key.' field.');
}
return $value;
}
?>
function verify_time_format()
function verify_time_format ($value) {
$pattern1 = '/^(0?\d|1\d|2[0-3]):[0-5]\d:[0-5]\d$/';
$pattern2 = '/^(0?\d|1[0-2]):[0-5]\d\s(am|pm)$/i';
return preg_match ($pattern1, $value) || preg_match ($pattern2, $value);
}
Returns TRUE for following values:
2:03:32
02:03:32
23:59:59
15:23 AM
15:23 am
09:41 pm
9:41 PM
etc...
Update:
function filter_time ($key, $value) {
$p1 = '/^(0?\d|1\d|2[0-3]):[0-5]\d:[0-5]\d$/';
$p2 = '/^(0?\d|1[0-2]):[0-5]\d\s(am|pm)$/i';
if (preg_match ($p1, $value) || preg_match ($p2, $value))
$res = date ('H:i:s', strtotime ($value));
else
display_error ("incorrect time format in {$key} field.");
return $res;
}
You're already using the strtotime from PHP, and for the values you specified there really is no need to force a specific format.
What you would likely want to test for and ensure, is that the field validates with only digits, the colon, and am or pm as in Wh1T3h4Ck5 answer.
With that in place, your code would likely be similar to the following
<?php
function valid_time($value) {//Wh1T3h4Ck5's function
return preg_match('/^(0?\d|1[0-2]):[0-5]\d\s(am|pm)$/i', $value);
}
$value = //some time;
if (vald_time($value)){
$time_value = strtotime($value);
echo $time_value;
}else{
die("Error incorrect time format, try again.");
}
?>
Though a more elegant solution would to look into using Jquery/Javascript PRIOR to the form being submitted. You can test and warn the user of improper format before submitting to the PHP script. Leave the validation in the PHP script though as well, with other safeguards if needed.
You can use a regular expression to solve the problem pretty easily. For example:
<?php
$databaseTimePattern = '/^(0[0-9])|(1[0-2]):[0-5][0-9]:[0-5][0-9]$/'; //Matches times in the form hh:mm:ss
$usaTimePattern = '/^([1-9]|(1[0-2])):[0-5][0-9] [a|p]m$/'; //Matches times in the form hh:mm am/pm
$value = //some time;
if (preg_match($databaseTimePattern, $value)){
// good no problem
}else if (preg_match($usaTimePattern, $value)){
$value = strtotime($value);
}else{
die("error incorrect time format, try again.");
}
?>

Categories