PHP - String does not get identified as date - php

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");

Related

How to force php strtotime to return today date if date variable is empty?

I have a js calendar in an HTML page and I'm passing the picked date into a PHP file. Currently, the date field is mandatory and it will display the default 1970/01/01 if no date is picked in the calendar.
I'm trying to change the behavior so that when no date is picked, then the current date will be passed into the PHP file.
The code in the PHP file is the one below:
$mydate = strtotime($_POST['mydate']);
$mydate = date("Y/m/d",$mydate);
How can I change it in order to display the current date if there's no value passed from $_POST['mydate']?
PS: I'm a newbie to PHP functions and searching for similar cases in the forums did not help.
The reason you get that is because strtotime returns false if it can't parse the date.
False is typecasted to 0, and date of 0 is 1970.
What you can do is to check if the strtotime return is false. (Not the same as isset or 0 in my opinion).
$mydate = strtotime($_POST['mydate']);
if($mydate === false){ // === is strict comparison
$mydate = date("Y/m/d");
}else{
$mydate = date("Y/m/d",$mydate);
}
Try this:
if( empty( $_POST['mydate'])){
$mydate = date("Y/m/d");
} elseif( FALSE !== $tm = strtotime( $_POST['mydate'])) {
$mydate = date("Y/m/d", $tm);
} else {
$mydate = date("Y/m/d");
}

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

Checking if a string has 07.05.2013 date format

Trying to validate a string to check if it has the format 07.05.2013, not sure how to approach it.
Thinking of checking if '.' are the 3rd and 6th characters, then checking if the rest of the characters are digits but I don't know how to achieve that.
If you simply need to parse the date, you can use the date time features of php.
<?php
$date = DateTime::createFromFormat('d.m.Y', '07.05.2013');
echo $date->format('Y-m-d');
?>
Use the DateTime::CreateFromFormat() method. This will validate your input and create a date object at the same time (which you can then use to work with the date).
$dateObj = DateTime::CreateFromFormat('d.m.Y', $inputString);
If the date is invalid or is in the wrong format, $dateObj will be false.
If it is a valid date in the required format, $dateObj will be a DateTime object.
Hope that helps.
if (preg_match('/^\d{2}\.\d{2}\.\d\{4}$/', $yourstring)) {
...
}
This will be true if your string matches expression like dd.dd.dddd where d is a digit.
You can also use the checkdate function:
$date= '07.05.2013';
$date_arr= explode('.', $date);
if (checkdate($date_arr[0], $date_arr[1], $date_arr[2])) {
// validate your date here
}
Something like:
$date = DateTime::createFromFormat('d.m.Y', $yourStringWhichMightBeADate);
if ($date)
{
// it's a date, so use it
}
Or:
$date = DateTime::createFromFormat('m.d.Y', $yourStringWhichMightBeADate);
if ($date)
{
// it's a date, so use it
}
if the month is first rather than the day of month.
SOLUTION 1:
Here's the way I did it, it works with every input you decide to enter (e.g: "12.02.1996", "12.30.1996", "dasdsadas", and so on..)
public function valid_date($inputdate){
$date = $inputdate;
if (strtotime($date)){
if (strpos($date,'.') !== false) {
list($day, $month, $year) = explode('/', $date);
return checkdate($month, $day, $year);
}else{
return false;
}
}else{
return false;
}
}
If input date is 10/10/1996 which is also a valid format, or 10/02/1996, it won't accept them because I'm asking the user to use the format with ".". Just remove the "if" if you don't want to do this validation and that is it.
SOLUTION 2:
Found this at php.net, very clean and interesting!
public function valid_date($date, $format = 'd.m.Y'){
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) == $date;
}

how to validate date with 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;
}

Categories