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
}
Related
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. :-)
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.
I made this function and it works:
$myHour = "09:09";
$myHour = time_format($myHour);
function time_format($h){
$initial_string = $h;
$new = substr($h,1,strlen($h));
$h = substr($h,0,-4);
if ($h == "0"){
return $new;
}else{
return $initial_string;
}
}
This function verify it the string looks like: "01:02" and get rid of the first "0", so it will become "1:02" else if it looks like "13:13" it will return "13:13".
My question is how to improve my function? or if there exists other better method ? thx
use ltrim to just simply remove the leading 0 if there is one. I assume there is a reason you cant just change the date format which generates the string ?
function time_format($h){
return ltrim($h, "0");
}
But changing the date format is the best option
this will be your shortened function, still readable
function time_format($h){
if (substr($h, 0, 1) == "0"){
return substr($h, 1);
}else{
return $h;
}
}
this would be even shorter
function time_format($h){
return substr($h, 0, 1) == "0" ? substr($h, 1) : $h;
}
this one is even without the if operators
to read more about it, here is a link.
<?php
$date = new DateTime('2000-01-01');
echo $date->format('Y-m-d H:i:s');
?>
Please have a detailed look here:
http://www.php.net/manual/en/datetime.format.php
You can get a DateTime object by UnixTimestamp (if needed) with this way
$dtStr = date("c", $timeStamp);
$date = new DateTime($dtStr);
Source: Creating DateTime from timestamp in PHP < 5.3
use PHP date function
try to google first..
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
}