I'm passing a date input using php $_GET
<form action="trigger_date.php" method="get">
Enter Project Turnover date (mm/dd/yy): <input type="string" name="date"> <input type="submit">
In the trigger_date.php takes this as
<?php $turnover_date = $_GET['date']; ?>
I do some math to compare it to today's date
<?php
$project_turnover = strtotime($turnover_date);
$project_turnover = date ("m/d/y", $project_turnover);
?>
<?php
$datetime1 = date_create($today);
$datetime2 = date_create($project_turnover);
$wks_to_turnover = date_diff($datetime1, $datetime2); // taking the difference between today and project turnover date
$wks_to_turnover = $wks_to_turnover->format('%R%a');
$wks_to_turnover = ($wks_to_turnover/7);
$wks_to_turnover = round($wks_to_turnover,1); //with input of 5/1/14 this should be roughly 24 wks
?>
Here's where I'm stumped, my styling is:
<?php
if ($wks_to_turnover > 2) {
echo $date_green; // colors the background green
} elseif (2 > $wks_to_turnover && $wks_to_turnover > 0) {
echo $date_yellow; // colors the background yellow
} elseif (0 >= $wks_to_turnover) {
echo $date_red; //colors the background red
} ?>;
But even if (24 > 2) it's still coloring as red
Note that <input type="string" /> is not valid HTML -- you're looking for type="text"
date_create accepts several different formats of dates. The m/d/y format, which you're using on the input date, is bad form because it is ambiguous. Per the manual:
Note:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at
the separator between the various components: if the separator is a
slash (/), then the American m/d/y is assumed; whereas if the
separator is a dash (-) or a dot (.), then the European d-m-y format
is assumed.
To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD)
dates or DateTime::createFromFormat() when possible.
Use a standardized date format that is supported by the Date object. It may not be the cause of your issue, but it is good to be unambiguous in code.
I'm not completely sure why you turn the input into a UNIX timestamp and then back to a formatted date. You could simply use the formatted date you get from input, which appears to be in a supported format, and deal with any errors that may generate.
Finally, your math produces a negative number. That's one reason why your logic fails to act as you expect. You can reverse the order of arguments passed to date_diff, OR use abs to get the absolute distance between the two dates. I went with abs, which makes the code not care if the 2 weeks is in the past or in the future. I don't know what you're doing here -- maybe the sign matters. If so, reverse the order of arguments passed to date_diff
(edit: OP clarified abs would not suite his need, adjusted accordingly)
Putting it together, I would suggest something like this:
$datetime1 = date_create('now');
$datetime2 = date_create(
array_key_exists(
'date',
$_GET
) ? $_GET['date'] : 'invalid'
);
if (!$datetime2)
die('invalid date');
$wks_to_turnover = date_diff($datetime2, $datetime1);
$wks_to_turnover = $wks_to_turnover->format('%R%a');
$wks_to_turnover = ($wks_to_turnover/7);
$wks_to_turnover = round($wks_to_turnover,1);be roughly 24 wks
if ($wks_to_turnover <= 0) {
echo 'green';
} elseif ($wks_to_turnover < 2 && $wks_to_turnover > 0) {
echo 'yellow';
} else {
echo 'red';
}
I also adjusted the final block of ifs -- if weeks is less than or equal to zero, green, if less than two but greater than 0 yellow, otherwise red.
Try it: http://codepad.viper-7.com/kLN5jk
Documentation
strtotime - http://www.php.net/manual/en/function.strtotime.php
DateTime::__construct - http://www.php.net/manual/en/datetime.construct.php
Date formats - http://www.php.net/manual/en/datetime.formats.date.php
date (documents format strings) - http://php.net/manual/en/function.date.php
abs - http://www.php.net/manual/en/function.abs.php
I tried your code and it return red when i pass "non numerical value" so , i tried
echo (int)$wks_to_turnover;
and it returned '0' , the reason because the date not returned as integer yet.
a quick fix for that using your approach
replace that line :
$wks_to_turnover = date_diff($datetime1, $datetime2);
with that :
$wks_to_turnover = strtotime($datetime1)-strtotime($datetime2);
it'll return the difference in seconds , you can handle it from here
Related
I'm trying to compare between two date but unfortunately this isn't working by converting this into UNIX format with strtotime. I'm trying to compare a date to another date.
However this format is working:
if(strtotime("22-04-17") < strtotime("25-05-17")){
echo 'Date One is smaller than date two';
}
But Many times it's failing. I've seen a lot of examples on the web but I can't figure out anything good!
if(strtotime("22-04-17") < strtotime("04-05-17")){ //passing still the
// bigger on but not working
echo 'Date One is smaller than date two';
}
From the manual (make special note of the part I've put in bold):
"Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed. If, however, the year is given in a two digit format and the separator is a dash (-, the date string is parsed as y-m-d."
So here's what you're doing, with the dates PHP is interpreting your strings as in comments:
// Is 17 April 2022 earlier than 17 May 2025? Yes.
if(strtotime("22-04-17") < strtotime("25-05-17")){
echo 'Date One is smaller than date two';
}
// Is 17 April 2022 earlier than 17 May 2004? No.
if(strtotime("22-04-17") < strtotime("04-05-17")){ //passing still the
// bigger on but not working
echo 'Date One is smaller than date two';
}
I hope this makes the problem you're having clear.
As it also says in the manual, use DateTime::createFromFormat/date_create_from_format if you want to avoid ambiguity:
$date = date_create_from_format('d-m-y', '04-05-17'); // 4 May 2017
your comparsion is not working because strtotime("22-04-17") actually results to timestamp for this date: 17th April 2022;
Do the following and you will see what I mean. the following code will output '2022-May-17`
$date = "22-05-17";
echo date ("Y-M-d ",strtotime($date))."<br>";
Try this
$date1 = date('d-m-y',strtotime("22-04-17"));
$date2 = date('d-m-y',strtotime("04-05-17"));;
if((int)strtotime($date1) < (int)strtotime($date2)){ //passing still the
echo 'Date One is smaller than date two';
}
Your year format 17 causing the problem in strtotime function
I know this isn't what you're looking for but have you tried doing this to showing if date greater / smaller?
// Dates
$Date1 = strtotime("22-04-17 GMT");
$Date2 = strtotime("04-05-17 GMT");
// Diff between dates
$Diff = (int)floor(($Date1 - $Date2) / (60*60*24));
if ($Diff < 0) {
echo "The Diff is negative";
}
Then the other way is like this answer: LINK
$date1 = strtotime("22-04-17 GMT");
$date2 = strtotime("04-05-17 GMT");
if((int)strtotime($date1) < (int)strtotime($date2)){ //passing still the
echo 'Date One is smaller than date two';
}
I wrote a function that takes your datestring and properly return timestmp. Please note that I followed PHP's convention of treating 2 digit years, i.e. 00-69 are mapped to 2000-2069 and 70-99 to 1970-1999
/* functon takes dateString of format dd-dd-yy and return proper timestamp */
function getTimestamp($dateString)
{
$res = preg_match('/^([0-9]{2})\-([0-9]{2})-([0-9]{2})/', $dateString, $matches);
if(!$res)
return 0;
//00-69 are mapped to 2000-2069 and 70-99 to 1970-1999
if($matches[3]>=70 && $matches[3]<=99 )
$year = "19".$matches[3];
else
$year = "20".$matches[3];
$formatted_dat_string = $year."-".$matches[2]."-".$matches[1];
return strtotime($formatted_dat_string);
}
getTimestamp("22-04-99");
So you can now use this function instead of strtotime for comparison.
Finally, I got the solution. The strtotime() isn't any good to handle this case. You should go for dateTime object instead.
//First you need to pass the original format then you will need to pass new
//Format to get this working properly. Hope this will help you guy's
$myDateTimestart = DateTime::createFromFormat('d-m-Y', $dateString);
$startDate = $myDateTimestart->format('m-d-Y');
//with Simply that you can format your date properly
I just Messed my times with this thing it was really bad
I am displaying a number of dates using PHP and I need to hide them when a certain date has expired.
I am using an IF statement to run this but it doesn't seem to be working.
Any suggestions would be great
<?PHP if('09-19-2016'<DATE('m-d-Y') || $_SESSION['role'] == 'Administrator') echo('<li>Week 2 - W/C 12/09/2016</li>');?>
When you're doing
'09-19-2016' < date('m-d-Y')
You're ending up comparing two strings, these can't be evaluated as "greater than" or "less than". You'll need to convert it to timestamps or use DateTime objects to do it. Also, the date format isn't correct.
<?php
$date_string = "09/19/2016";
// Using objects
$current_date = new DateTime();
$your_date = new DateTime($date_string);
if ($your_date < $current_date || $_SESSION['role'] == 'Administrator')
echo'<li>Week 2 - W/C 12/09/2016</li>';
// Using timestamps
if (strtotime($date_string) < time() || $_SESSION['role'] == 'Administrator')
echo'<li>Week 2 - W/C 12/09/2016</li>';
Choose either one of the above - both will work, although I find objects easier to work with.
From your comments,
hide the date if the date has passed
Note that when using the less than operator <, doing $date < $now will evaluate to true if the date is in the past, and hide the content if the date is in the future. If you desire the opposite behavior, you just use the greater than operator <.
Here's a live demo: https://3v4l.org/N74G2
References
http://php.net/datetime.construct
http://php.net/strtotime
http://php.net/language.operators.comparison
You need to parse your date from your format '09-19-2016' to a timestamp or DateTime object, which PHP will be able to compare as a date. You can use PHP's date_parse_from_format() to do so.
For example:
$date = '09-19-2017';
$parsed = date_parse_from_format('m-d-Y', $date);
$timestamp = mktime(
$parsed['hour'],
$parsed['minute'],
$parsed['second'],
$parsed['month'],
$parsed['day'],
$parsed['year']
);
if ($timestamp < time()) {
echo 'older';
} else {
echo 'newer';
}
This will give you the correct answer while keeping your current format. You can see an working example here: https://3v4l.org/NIoId
I have a date stored in my DB (due_date)
I am wanting to write a script that checks if the due_date is in the next 3 days
From checking online (google) i have found some code but it doesnt seem to work, see below
if (time() - filemtime($due_date) >= 3 * 86400)
{
echo" Invoice $id is due in the next 3 days<br />";
}
else
{
echo" Invoice $id not due in the next 3 days </br>";
}
$due_date contains a date in the format 01/01/2015
Please can someone help with this? P.s I am a newbie!
Thanks
Use strtotime() to convert the date string to a unix timestamp, and edit your if statement accordingly:
$seconds_to_expire = strtotime($due_date) - time();
if ($seconds_to_expire < 3*86400) {
...
Note that dates in the m/d/y or d/m/y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed (see this). You may want to convert your date to a Y-m-d format instead:
$due_date_ymd = date('Y-m-d', strtotime(str_replace('/', '-', $due_date));
$seconds_to_expire = strtotime($due_date_ymd) - time();
if ($seconds_to_expire < 3*86400) {
...
Change
filemtime($due_date)
to
strtotime(str_replace('/', '-', $due_date))
you have to change / to - if the day comes first, otherwise php will assume that first is month!
if (strtotime($due_date)+60*60*24*3 =< time()+60*60*24*3) {
echo "Is due in the next 3 days"
} else {
echo "Is not due in the next 3 days"
}
You could translate the DB date value (which is in the format 'yyyy-mm-dd') to a DateTime object and then compare:
$d = DateTime::createFromFormat('Y-m-d', $due_date);
$d->modify('-3 days'); // subtract 3 days from due date
if ($d < new DateTime()) {
echo 'date is due within 3 days';
}
Notes:
new DateTime() will give you the current date.
I assume that $due_date is a string in the format 'yyyy-mm-dd', as you should get if it is a Date column in the database.
Since you commented that $due_date is "A date in the format 01/01/2015", you can easily ajust the code: change the format specifier in the createFromFormat function from 'Y-m-d' into 'd/m/Y'.
I am trying to convert a user inputted date so I can use it to search in MySQL. This is my code -
<form name="date_form" action="" method="POST"">
<input type="text" name="start_date" value="<?php echo date('d/m/Y');?>"/>
<input type="submit" name="submit_start" value="Submit" />
<?php
if(isset($_POST["submit_start"]))
{
$date_1 = mysqli_real_escape_string($dbc, trim($_POST['start_date']));//checking that I am getting something from the input
$newDate = date("Y-m-d", strtotime($_POST['start_date']));//converting date from the input to SQL format
echo '<br>date 1 = '.$date_1.'<br>';
echo 'date 2 = '.$newDate.'<br>';
$start_date = '2013-12-13';
echo 'date 3 = '.$start_date.'<br>';//Just to compare formats
$report = create_user_report($dbc, $start_date);
}
and this is the output
date 1 = 14/12/2013
date 2 = 1970-01-01
date 3 = 2013-12-13
2013-12-13
I was expecting date 2 to be 2013-12-13, the format appears to be ok but the value isnt. I have played with many different ways of getting the value, all have been wrong!
So I have two questions please
1. How can I get the correct value in the code above?
2. I want to use this value to search a MySQL table and return a count of dates that match it. Once the above is working, is that the best way to do it - or is there a better way?
Many thanks
From the strtotime manual:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between
the various components: if the separator is a slash (/), then the American m/d/y is
assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y
format is assumed.
So:
$newDate = date("Y-m-d", strtotime($_POST['start_date']))
is asking for the 12th day of the 14th month.
Try replacing the / with -
$date = str_replace ( '/' , '-' , $_POST['start_date'])
The problem is caused because when confronted with /, strtotime assumes the time to be in the American format of m/d/Y (instead of d/m/Y). Read the manual on strtotime (especially the Notes) for more information.
And because 14/12/2013 is not valid in the American format, you'll get the default time (aka UNIX timestamp 0).
Since this is user input and you cannot be sure if he really means to use the American format or is misusing it, you could do a check before the conversion like this
//check if input is a date in the American format
if (preg_match("#^(\d+)/(\d+)/(\d+)$#", $_POST['start_date'], $matches)) {
if ($matches[1] > $matches[2]) {
$day = $matches[1];
$month = $matches[2];
} else {
$day = $matches[2];
$month = $matches[1];
}
$start_date = $month.'/'.$day.'/'.$matches[3];
}
However if a user inputs e.g. 04/05/2013 this will be interpreted in the American format, although the user could have meant it in d/m/Y.
"Explode" seems to be commonly used in situations like this.
$mydate = $_POST["submit_start"];
list ($y, $m, $d) = explode('/', $mydate);
$mydate = sprintf("%02d-%02d-%04d", $m, $d, $y);
strtotime requires the English date format as input - HERE.
strtotime() PHP Manual
Take a look over there, it reports
The function expects to be given a string containing an English date format
And that's why your function doesn't work as you expect. In fact, d/m/Y is NOT an american date format. Here, take a look, I made you some examples to let you see how to make it work: Click here - eval.in
<?php
echo strtotime(date('m/d/Y'));
echo strtotime(date('d/m/Y'));
echo strtotime(date('d-m-Y'));
echo strtotime(date('d/m/Y'));
echo strtotime(date('Y-m-d'));
echo strtotime(date('Y/m/d'));
?>
Produces
1386979200
FALSE
1386979200
FALSE
1386979200
1386979200
Since you'll never know what kind of date format (or if it's actually a date at all) an user may input, I suggest you to use a date picker plugin on your input, that'll be very useful, or you may want to use a regular expression that other user suggested.
For the mysql part you can easly compare two dates with the MySQL Date Function
Since I don't know your query I'll just provide you the part you need for the comparsion in the query:
... WHERE DATE(some_date) = DATE(some_other_date) ...
Where some_date and some_other_date are two valid date formats as written above.
I have a string "date" which can be DD.MM.YYYY or D.M.YYYY (with or without leading zeros), it depends what a user types.
Then I use it in a condition to send another email when the day is today.
if($_POST["date"]== date("d.m.Y")){
$headers.="Bcc: another#mail.cz\r\n";
}
The problem is that the mail is send when the date format DD.MM.YYYY (with leading zeros) only.
My proposed solution
As I'm not very good in PHP, I only know the solution theoretically but not how to write the code - I would spend a week trying to figure it out on my own.
What's in my mind is dividing the date into three parts (day, month, year), then checking the first two parts if there's just one digit and adding leading zeros if it's the case. I don't know how to implement that to the condition above, though. I have read a few topics about how to do this, but they were a bit more different than my case is.
You should equalize to same format d.m.Y and you can do this with strtotime and date function:
$post_date = date("d.m.Y", strtotime($_POST["date"]));
if($post_date == date("d.m.Y")){
$headers.="Bcc: another#mail.cz\r\n";
}
I changed date to $post_date for more clear. I'll try to explain difference with outputs
echo $_POST["date"]; // lets say: 8.7.2013
echo date("d.m.Y"); // 09.09.2013 > it's current day
strtotime($_POST["date"]); // 1373230800 > it's given date with unix time
$post_date = date("d.m.Y", strtotime($_POST["date"])); // 08.07.2013 > it's given date as right format
If you use date function without param, it returns as current date.
Otherwise if you use with param like date('d.m.Y', strtotime('given_date'));, it returns as given date.
$post_date = date("d.m.Y", strtotime($_POST["date"]));
At first, we converted your date string to unix with strtotime then equalized and converted format that you used in if clause.
first set date format with leading Zero
$postdate = strtotime('DD.MM.YY', $_POST['date']);
and also matching date will be in same format
$matching_date = date('DD.MM.YY', strtotime('whatever the date'));
then
if ( $postdate === $matching_date )
{
// send mail
}
Why don't you just check the length of the _POST (it can be either 8 or 10)
if (strlen($_POST["date"]) == 10) {
$headers.="Bcc: another#mail.cz\r\n";
}