I'm trying to validate dates in PHP, but the problem is that with some dates work, an example would be: "02/2/2015" returns true, "20/12/2015" false returns, is a serious problem and I see no error in the code.
Function.
<?php
function check_date($date) {
$open_date = explode('/', $date);
if (count($open_date) == 3) {
if (checkdate($open_date[0], $open_date[1], $open_date[2])) {
return true;
} else {
return false;
}
} else {
return false;
}
}
//$date = "02/2/2015"; // return true !
$date = "20/12/2015"; // return false ?
if(check_date($date)) {
echo "valid";
} else {
echo "invalid";
}
?>
How could solve this problem?
checkdate expects a month, day and year, in that order:
https://secure.php.net/manual/en/function.checkdate.php
If your dates are formatted as day/month/year then you can still use checkdate, you'll just have to change the order of the parameters:
if (checkdate($open_date[1], $open_date[0], $open_date[2]))
The signature of checkdate function looks like checkdate(month,day,year); . You can have upto 12 months and not 20. :-)
Related
It's supposed to be blank. How can I prevent this from happening?
I am using this code to show the date
public function bookedOn($chalet_id) {
$chalet = \App\Chalet::where('chalet_id', '=', $chalet_id)->get();
if ($chalet->count() > 0) {
$books = \App\EventBookings::where('chalet_id', '=', $chalet[0]->chalet_id)->value('created_at');
$str = date('M. d, Y',strtotime($books));
return $str;
} else {
return false;
}
}
I think there is something I need to do here:
$str = date('M. d, Y',strtotime($books));
It is taking a default date which is Dec. 31, 1969 if you are returning false. I mean, if you are not finding any $chalet value. You can avoid it by returning a default date or you can check for returned false value and put empty date or a default date on your view.
If it do not solve your problem then check whether the $book is empty or not.
Update
Thank you for your compliment. Some more thoughts, you must not remove the else part. Because if your condition do not satisfy then nothing will be returned. So you will get nothing. For this you can return the current date date('M. d, Y') there (not sure if it matches your functionality). And it is better to set current date rather than using a default date. So your code could be something like this
public function bookedOn($chalet_id) {
$chalet = \App\Chalet::where('chalet_id', '=', $chalet_id)->get();
if ($chalet->count() > 0) {
$books = \App\EventBookings::where('chalet_id', '=', $chalet[0]->chalet_id)->value('created_at');
if(!empty($books)){
$str = date('M. d, Y',strtotime($books));
}else{
$str = date('M. d, Y');
}
return $str;
} else {
return date('M. d, Y');
}
}
Try like this:
public function bookedOn($chalet_id) {
$chalet = \App\Chalet::where('chalet_id', '=', $chalet_id)->get();
if ($chalet->count() > 0) {
$books = \App\EventBookings::where('chalet_id', '=', $chalet[0]->chalet_id)->value('created_at');
if ($books == '') {
// some default date
$books = '2010-01-01';
}
$str = date('M. d, Y',strtotime($books));
return $str;
} else {
return false;
}
}
For some reason this is always returning false... when entering "2014 12 12" into the form. It is this format to enter into a database.
$date = trim($_POST['date']);
in my library.php i have :
function validateDate($date) {
if(preg_match('/^[0-9]{2,4}[\-[[:space:]]]{1}[0-9]{1,2}[\-[[:space:]]]{1}[0-9]{1,2}$/',$date)){
return true;
}
else{
return false;
}
}
and in my php i have :
if (validateDate($date)){
$dateCSS = 'style="border-color: #98faad;"';
}
else {
$dateCSS = 'style="border-color: red;"';
$flag = false;
}
Try this regexp:
^[0-9]{2,4}[\-[:space:]]{1}[0-9]{1,2}[\-[:space:]]{1}[0-9]{1,2}$
A more reliable way to validate a date is to use the datetime extension.
function validateDate($date, $format = 'Y d m') {
return \DateTime::createFromFormat($format, $date) !== false;
}
This way you do not have to resort to using regular expressions, and you will be able to actually validate dates correctly (for example, something like 2014 12 51 will not validate).
if ( ! validateDate('2014 12 51')) {
echo 'Not valid!';
}
It will also allow you to validate more complicated dates, if you will be required to do that some day:
if (validateDate('16th September 2014', 'dS F Y')) {
echo 'Valid!';
}
For the $format argument you must use the formatting options that DateTime::createFromFormat() accepts.
im trying to validate a date in the YYYY-MM-DD in the $immerseusnorm i have tried the code below but its returning No!
<?php
$json = file_get_contents("http://www.wowtrack.org/plugins/guild/EU/Emerald%20Dream/VII?format=json", true);
$decode = json_decode($json, true);
$realmrank = " ". $decode[realmRank] ."";
$immerseusnorm = " ". $decode[encounters][0][completedOn]."";
if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/",$immerseusnorm))
{
$immerseusnorm = "Yes";
}
$immerseusnorm = "No";
echo "Realm Rank: $realmrank<br \>";
echo "Immerseus Normal - Completed On: $immerseusnorm<br \>"
Any help would be great
Thanks
I would attempt to create a DateTime object based on the format. That way, you can validate both the format AND that the date it suggests is valid. For example, a simple regex match with your pattern would allow something like 2014-02-31, which obviously is not a valid date.
The only challenge with DateTime is that a date like 2014-02-31 gets "fixed" to 2014-03-03, instead of returning false from DateTime::createFromFormat(). So you can just check back against the input string to make sure the date didn't get changed.
Putting it into a function could look like this:
function validate_date($input_date, $format = 'Y-m-d') {
$datetime = DateTime::createFromFormat($format, $input_date);
if(false === $datetime) {
return false;
} else if ($datetime->format($format) === $input_date) {
return true;
} else {
return false;
}
}
// usage
if (validate_date($immerseusnorm)) {
// validation passed
} else {
// validation failed
}
I guess you should add else around the second $immerseusnorm, it now always sets it to no. So better change this:
if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/",$immerseusnorm))
{
$immerseusnorm = "Yes";
}
$immerseusnorm = "No";
to:
if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/",$immerseusnorm))
{
$immerseusnorm = "Yes";
}else{
$immerseusnorm = "No";
}
It seems that your regex is working.
you have missed a point here.
this line is always executed :
$immerseusnorm = "No";
You should have else of your if condition.
try this:
if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/",$immerseusnorm))
{
$immerseusnorm = "Yes";
}
else{
$immerseusnorm = "No";
}
Sample demo : see demo : https://eval.in/107333
This should be very easy, but I am not getting it. I wish to receive hours:minutes, and return hours:minutes:seconds in 00:00:00 format. The following falls way short. Recommendations on the best way to do this? Thank you
<?php
function fixTime($t)
{
$a = explode(':', trim($t));
return ((count($a)==2) && ($h=$a[0]) && ($m=$a[1]) && ($h>=0) && ($m>=0) && ($h<=23) && ($m<=59))?$h.':'.$m.':00':'00:00:00';
}
echo(fixTime('23:33').'<br />');
echo(fixTime('05:00').'<br />');
echo(fixTime('5:00').'<br />');
?>
The strtotime function will help you out here:
function fixTime($t) {
return date('H:i:s', strtotime($t));
}
echo fixTime('23:33'); // 23:33:00
echo fixTime('05:00'); // 05:00:00
echo fixTime('5:00'); // 05:00:00
Also, see the date function for a list of formatting options available.
To validate such simple input, a regular expression might be helpful:
function fixTime($t) {
if (!preg_match('/^([01][0-9]|2[0-3]|[0-9]):[0-5][0-9]$/', $t)) {
return false;
}
return date('H:i:s', strtotime($t));
}
echo fixTime('23:33'); // 23:33:00
echo fixTime('33:33'); // false
if (fixTime('33:33') === false) {
// invalid date supplied
}
When a user enters a date in text box,i've to check ,whether it is in yyyy-mm-dd format.
Note Even month,date,for eg:2012-02-32 is not valid because,date can be only till 31 and same for month,he can n't enter month as 13.
If it is in wrong format,i should echo.
Thanks in advance!
Try this
list($year,$month,$day) = explode('-', $input);
if (checkdate($month, $day, $year)) {
// Correct
} else {
// Incorrect
}
Reading comments on http://php.net/manual/en/function.checkdate.php is quite informative, including validating through regexp.
I use the following code from that page:
function checkDateTime($data) {
if (date('Y-m-d', strtotime($data)) == $data) {
return true;
} else {
return false;
}
}
Also I'd recommend adding JavaScript datepicker http://jqueryui.com/demos/datepicker/
$e = explode('-', '2012-02-32');
if (checkdate($e[1], $e[2], $e[0])){
// Valid
}else{
// Invalid
}
http://php.net/manual/en/function.checkdate.php
that's exactly what you need: http://php.net/manual/en/function.checkdate.php
You should not use regular expressions for this. A better (maybe not the best) is to use checkdate();
$parts = explode('-', $input);
if (sizeof($parts) == 3 && checkdate($parts[1], $parts[2], $parts[0])) {
// Correct
} else {
// Incorrect
}