Checking date issue - php

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

Related

Getting date from a string without time in php

I have to convert a string input to date "1990/07/22" to 22/07/1990 as date,My function is as follows as:
public function($date){
$date_format_sec = strtotime($date);
$date_of_birth = new \DateTime('#'.$date_format_sec);
}
It uploads date as 21/07/1990 since I didn't give time.How to get the exact date given as same as input.
You can format your date with php
$formatedDate = $date_of_birth->format('d-m-Y');
Documentation
$input = '1990/07/22';
$date = \DateTime::createFromFormat('Y/m/d', $input)->format('d-m-Y');
As I said, you don't need to use strtotime, if the $date string is a valid date, the class DateTime will read it. After that you can use format.
In this example I set the format to be always the one you expect, while you can put any other format accepted by it.
public function getMyDate($date, $format = 'd/m/Y') {
$date_of_birth = new \DateTime($date);
return $date_of_birth->format($format);
}
public function formatDate($date) {return date('d/m/Y', strtotime($date));}

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

Call to a member function format() on boolean

I want to find the difference between two dates and I have used date_diff for the same. When format function is applied on date_diff object it returns an error.
Call to a member function format() on boolean
$field_value is fetched from the database and it's format is dd/mm/YYYY. When I hard-code the values for $field_value and $indexing_value the following code works.
Everything is running fine till line number 8. I have tried outputting the value of
$diff->format("%R%a")
and it is returning exact value but the code gives error near the if statement.
$date = new DateTime();
$current_date = $date->format('d/m/Y');
$indexing_value = str_replace("/", "-", $field_value);
$current_value = str_replace("/", "-", $current_date);
$indexing_value = date_create($indexing_value);
$current_value = date_create($current_value);
$diff = date_diff($indexing_value, $current_value);
if ($diff->format("%R%a") < 0) {
echo "1";
} else {
echo "2";
}
Please let me know what is wrong with the above code.
add condition to check whether you got the diff or not, as it returns false if there is error . Check manual for the same
$diff = date_diff($indexing_value, $current_value);
if ($diff) {
if ($diff->format("%R%a") < 0) {
echo "1";
}else{
echo "2";
}
}
You are getting error because for some values the diff is not calculated and have value False in $diff
Please let me know what is wrong with the above code.
There are several issues with the code:
You don't check the values returned by date_create(); it returns FALSE on error.
What's the point of formatting $date then creating $current_value back from the resulting string? If you don't care about the time components and need to use only the date part of a DateTime object you can use its setTime() method to set the time components to 0.
What's the point of using str_replace() to manipulate the text representation of a date when you know its format? DateTime::createFromFormat() can be used to parse the string into a DateTime object.
There is no need to compute the difference of the two dates and the format it and compare the value to 0. The DateTime objects can be compared directly.
All in all, all the code you need is:
// Current date & time
$today = new DateTime();
// Ignore the time (change $today to "today at midnight")
$today->setTime(0, 0, 0);
// Parse the value retrieved from the database
$field = DateTime::createFromFormat('d/m/Y', $field_value);
// We don't care about the time components of $field either (because the time
// is not provided in the input string it is created using the current time)
$field->setTime(0, 0, 0);
// Directly compare the DateTime objects to see which date is before the other
if ($field < $today) {
echo "1";
} else {
echo "2";
}

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;
}

Validating a date dd/mm/yyyy

Does anyone know of any good functions for validating a date via input text box in codeigniter like this: dd/mm/yyyy? Thanks
You're probably looking for the strptime function. For the specified format you can use it like this:
$result = strptime($input, '%d/%m/%Y');
$resultwill be either false if the input is invalid or on array with the date.
Or if you're on Windows or have PHP >= 5.3, consider using date_parse_from_format.
Use strtotime function.
$date = strtotime($input);
returns false if invalid, or -1 for php4.
you could also use a custom callback function
<?php
function valid_date($date)
{
$date_format = 'd-m-Y'; /* use dashes - dd/mm/yyyy */
$date = trim($date);
/* UK dates and strtotime() don't work with slashes,
so just do a quick replace */
$date = str_replace('/', '-', $date);
$time = strtotime($date);
$is_valid = date($date_format, $time) == $date;
if($is_valid)
{
return true;
}
/* not a valid date..return false */
return false;
}
?>
your validation rule looks like:
$rules['your_date_field'] = "callback_valid_date";
dont know about codeigniter but there's some alike already in php already
checkdate();

Categories