how to validate date with PHP - php

If a date is submitted by form in following format, $month=2, $day=31, $year= 2010. How can i verify using PHP date function if it is valid date or not? Thanks.

http://php.net/manual/en/function.checkdate.php
The checkdate function is the first result in google from the search "php validate date"
In your case, the usage would be:
checkdate($month, $day, $year);

<?php
function validateDate($date, $format = 'Y-m-d H:i:s'){
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) == $date;
}
?>
var_dump(validateDate('2012-02-28 12:12:12')); # true
var_dump(validateDate('2012-02-30 12:12:12')); # false
var_dump(validateDate('2012-02-28', 'Y-m-d')); # true
var_dump(validateDate('28/02/2012', 'd/m/Y')); # true
var_dump(validateDate('30/02/2012', 'd/m/Y')); # false
function was copied from this answer or php.net

Try checkdate()
http://php.net/manual/en/function.checkdate.php
checkdate($month, $day, $year);
returns true if date is valid / false otherwise

bool checkdate ( int $month , int $day , int $year )

Here's what I've come up with to combine the strictness of checkdate() with the convenience of DateTime (It converts entries like 'next thursday' or '2 weeks ago')
If the input string is invalid, it returns false. Empty dates are returned as null, and non-empty dates are formatted MySQL style 'Y-m-d'.
/**
* #return variant null for empty date, mysql date string for valid date, or false for invalid date string
*/
function myCheckDate($date)
{
$result=false;
if($date=='')
{
$result=null;
}
else
{
//Best of both worlds
// - flexibility of DateTime (next thursday, 2 weeks ago, etc)
// - strictness of checkdate (2000-02-31 is not allowed)
$m=false;
$d=false;
$y=false;
$parts=date_parse($date);
if($parts!==false)
{
$m=$parts['month'];
$d=$parts['day'];
$y=$parts['year'];
}
if($m!==false && $d!==false)
{
if($y===false) $y=date('Y'); //Default to this year
//Try for a specific date - this catches bad entries like 'feb 31, 2000'
if(checkdate($m,$d,$y)) $result=sprintf('%04d-%02d-%02d',$y,$m,$d);
}
else
{
//Try for something more generic - this allows entries like 'next thursday'
$dt=false;
try{ $dt=new \DateTime($date); }catch(\Exception $e){ $dt=false; }
if($dt!==false) $result=$dt->format('Y-m-d');
}
}
return $result;
}

Related

PHP - String does not get identified as date

Hi I have a function that checks to see if a user input string is a valid date. The user has to input the date in the format 25-January-2018 and it checks to see if it can be converted to the format 25-01-2018. However when I test the function using a date where both the month and day are single digits then it returns false even though a valid date has been entered.
function validateDate($date){
$d = DateTime::createFromFormat('d-F-Y', $date);
return $d && $d->format('j-F-Y') === $date;
}
echo validateDate("03-February-2018"); //Returns false when it should be true
You should replace the j-F-Y with d-F-Y.
j means 1 to 31 while d means 01 to 31 then your two formats are different for the given date.
The following code works:
function validateDate($date){
$d = DateTime::createFromFormat('d-F-Y', $date);
return $d && $d->format('d-F-Y') === $date;
}
var_dump(validateDate("03-February-2018"));
Your function could work :
return $d && $d->format('d-F-Y') === $date;
but if your want to check if it's a valid date use this :
DateTime::createFromFormat('d-F-Y', "03-February") // returns false if not a valid date & Object if valid
Use strtotime() function better.
function validateDate($date){
$timestamp = strtotime($date);
$newDate = date('d-F-Y', $timestamp);
return ($timestamp && $newDate);
}
echo validateDate("03-February-2018");

Date not showing correctly as I input

if ($this->request->is('post')) {
$this->Operation->create();
if(!isset($this->request->data['Operation']['date_alarma'])){
$this->request->data['Operation']['date_alarma']= date('Y-m-d H:i:s',strtotime($this->request->data['Operation']['date_alarma'].' '.$this->request->data['Operation']['alarmA']['hour'].$this->request->data['Operation']['alarmA']['min']));
}
else if(!isset($this->request->data['Operation']['date_alarmb'])){
$this->request->data['Operation']['date_alarmb']= date('Y-m-d H:i:s',strtotime($this->request->data['Operation']['date_alarmb'].' '.$this->request->data['Operation']['alarmB']['hour'].$this->request->data['Operation']['alarmB']['min']));
}
else if(isset($this->request->data['Operation']['date_alarmcc'])){
pr($this->request->data['Operation']['date_alarmcc']) ;
$a= date('Y-m-d',strtotime($this->request->data['Operation']['date_alarmcc']));
pr($a); die;
}
The output showing like this
30/05/2015
1970-01-01
May I know why? The date I enter is 30/05/2015 at field date_alarmcc
strtotime() will interpret this format as m/d/Y, not d/m/Y and thus will return false because there is no 30th month.
echo (int) strtotime('05/30/2015');
// 1432969200
echo (int) strtotime('30/05/2015');
// 0
However, strtotime() will evaluate d-m-Y:
echo (int) strtotime('05-30-2015');
// 0
echo (int) strtotime('30-05-2015');
// 1432969200
Unix timestamps represent the number of seconds passed from 1970-01-01 so this represents the timestamp 0 because of the false return value from strtotime().
If you always want to use the d/m/Y format. You could easily replace / with - using str_replace():
$date = str_replace('/', '-', $date);
Thus it will be evaluated as d-m-Y correctly.

Checking date issue

I'm trying really hard to do some date validation. I have created like 3 different functions, they all work but not in special cases.
The last thing I did was this:
public function valid_date($date, $format = 'd/m/Y'){
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) == $date;
}
I got this function from php site, and like I thought it worked better than mine I replaced it.
The date format the user has to input is dd/mm/YYYY and in the database format is yyyy-mm-dd 00:00:00
When i enter this invalid date: 30/30/1996 the function recognizes it as a valid date. Then I have this other function to explode the "/" and to make it like the database format with "-" and in that function it gives me the error:
DateTime::__construct(): Failed to parse time string (1996-30-30) at position 6 (0): Unexpected character'
public function explodingDates($date){
list($day,$month,$year) = explode('/', $date);
$newDate = $year.'-'.$month.'-'.$day;
return (new \Datetime($newDate));
}
I'm burning my brain here, don't know what else to do for the validation. It also has to be prepared to receive any kind of input (like "askhdakjdh", "123213", "1.25/269") and return an invalid date.
Thanks in advance
Don't explode date strings. Use DateTime::createFromFormat() to create the DateTime object, and use the format() method to convert it into a different format:
function ConvertToMySQLDate($datestr) {
$d = DateTime::createFromFormat('d/m/Y', $datestr);
$valid = $d && $d->format('d/m/Y') == $datestr;
if ($valid) {
return $d->format('Y-m-d');
}
return FALSE;
}
The above function accepts a date string in the format dddd-mm-yyyy, checks if it is valid, and returns the date in MySQL format (yyyy-mm-dd). It returns false if the supplied date is not valid.
Example usage:
var_dump(ConvertToMySQLDate('30/30/1996')); // bool(false)
var_dump(ConvertToMySQLDate('13/12/1996')); // string(10) "1996-12-13"
Demo

Check PHP datetime stamp is correct?

Is there a way of checking whether a date time stamp is correct in PHP?
I am currently using yyyy-mm-dd hh:mm:ss in MySQL and would like to ensure when a user provides the date/time stamp in a form it matches the correct format.
[until someone comes with good (bugfree), working checkdate() example ]
I am using this function:
<?php
function validateMysqlDate( $date ){
if (preg_match("/^(\d{4})-(\d{2})-(\d{2}) ([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/", $date, $matches)) {
if (checkdate($matches[2], $matches[3], $matches[1])) {
return true;
}
}
return false;
}
// check it:
$a = validateMysqlDate('2012-12-09 09:04:00');
$b = validateMysqlDate('20122-12-09 09:04:00');
$c = validateMysqlDate('2012-12_09 09:04:00');
$d = validateMysqlDate('');
var_dump( $a );
var_dump( $b );
var_dump( $c );
var_dump( $d );
?>
and btw: checkdate() would return true for $b although it is not a valid mysql datetime
You can use the checkdate() function to check the validity of a date.
http://php.net/manual/en/function.checkdate.php
You can also pass all of the parts of your timestamp to mktime() and if false or -1 is returned (depending on PHP version) then it's an invalid date
http://www.php.net/manual/en/function.mktime.php
This a duplicate question. For additiona discussion and answers see MySQL: How to check if a string is a valid DATE, TIME or DATETIME
Try to parse the given string and then check it is the same date that you entered, note the below:
$dt = DateTime::createFromFormat('Y-m-d H:i:s', '2011-01-32 12:00:00');
echo $dt->format('Y-m-d H:i:s');
// outputs 2011-02-01 12:00:00
HTH.

$var is valid unix timestamp

I need a function to validate if the content of a variable is a valid unix timestamp.
I've checked this thread: Check whether the string is a unix timestamp but the problem is that the function in the most voted answer still can cause some errors, for eg:
function is_timestamp($timestamp)
{
return ((string) (int) $timestamp === $timestamp)
&& ($timestamp <= PHP_INT_MAX)
&& ($timestamp >= ~PHP_INT_MAX);
}
// Some tests:
$timestamp = 1289216307;
var_dump(is_timestamp($timestamp));
var_dump(date('Y-m-d', $timestamp));
// result
bool(false)
string(10) "2010-11-08"
$timestamp = '20101108';
var_dump(is_timestamp($timestamp));
var_dump(date('Y-m-d', $timestamp));
// result
bool(true)
string(10) "1970-08-21"
Here, the first should be TRUE and the second should be FALSE so, what's the best way to test if a $var is a real valid unix timestamp?
Here, the first should be TRUE and the second should be FALSE
Why? 20101108 is a valid UNIX timestamp, - as you say, it's August 21, 1970. Could well be a person's birthday for example.
The only way to achieve what you want is to set a range of dates that mark a "sane" timestamp by the definition you are working with - e.g. anything after January 1st, 2000 - and do a check against that.
A workaround for this would be to check if strtotime recognises the string as a valid date string.
function is_timestamp($timestamp)
{
return ((string) (int) $timestamp === $timestamp)
&& ($timestamp <= PHP_INT_MAX)
&& ($timestamp >= ~PHP_INT_MAX)
&& (!strtotime($timestamp));
}
This will weed out strings that are probably date strings rather than timestamps. It is probably easier to code than writing your own sanity checks.
You can check unix timestamp format using regular expression when your timestamp is bigger than size of integer:
/**
* Check if timestamp is in unix format.
*
* #param string $timestamp
* Target timestamp that will be checked.
*
* #return bool
* TRUE if timestamp is in unix format. FALSE on failure.
*/
function is_unix_timestamp($timestamp) {
return preg_match('/^\d+$/', $timestamp);
}
Write your own ;)
Some things you could check:
Is the given parameter an int? if not => false
Is it negative or above max? => false
Everything else is true
This would work for your given tests.
Any number is potentially a timestamp. The only significant difference between your two examples is that the latter case is a string. In which case:
function is_timestamp($timestamp) {
return is_int($timestamp) || is_float($timestamp);
}
(is_numeric is no good as it also returns true for strings that can be parsed as numbers.)

Categories