php date validation - php

Im trying to to set up a php date validation (MM/DD/YYYY) but I'm having issues. Here is a sample of what I got:
$date_regex = '%\A(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d\z%';
$test_date = '03/22/2010';
if (preg_match($date_regex, $test_date,$_POST['birthday']) ==true) {
$errors[] = 'user name most have no spaces';`

You could use checkdate. For example, something like this:
$test_date = '03/22/2010';
$test_arr = explode('/', $test_date);
if (checkdate($test_arr[0], $test_arr[1], $test_arr[2])) {
// valid date ...
}
A more paranoid approach, that doesn't blindly believe the input:
$test_date = '03/22/2010';
$test_arr = explode('/', $test_date);
if (count($test_arr) == 3) {
if (checkdate($test_arr[0], $test_arr[1], $test_arr[2])) {
// valid date ...
} else {
// problem with dates ...
}
} else {
// problem with input ...
}

You can use some methods of the DateTime class, which might be handy; namely, DateTime::createFromFormat() in conjunction with DateTime::getLastErrors().
$test_date = '03/22/2010';
$date = DateTime::createFromFormat('m/d/Y', $test_date);
$date_errors = DateTime::getLastErrors();
if ($date_errors['warning_count'] + $date_errors['error_count'] > 0) {
$errors[] = 'Some useful error message goes here.';
}
This even allows us to see what actually caused the date parsing warnings/errors (look at the warnings and errors arrays in $date_errors).

Though checkdate is good, this seems much concise function to validate and also you can give formats. [Source]
function validateDate($date, $format = 'Y-m-d H:i:s') {
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) == $date;
}
function was copied from this answer or php.net
The extra ->format() is needed for cases where the date is invalid but createFromFormat still manages to create a DateTime object. For example:
// Gives "2016-11-10 ..." because Thursday falls on Nov 10
DateTime::createFromFormat('D M j Y', 'Thu Nov 9 2016');
// false, Nov 9 is a Wednesday
validateDate('Thu Nov 9 2016', 'D M j Y');

Instead of the bulky DateTime object .. just use the core date() function
function isValidDate($date, $format= 'Y-m-d'){
return $date == date($format, strtotime($date));
}

Use it:
function validate_Date($mydate,$format = 'DD-MM-YYYY') {
if ($format == 'YYYY-MM-DD') list($year, $month, $day) = explode('-', $mydate);
if ($format == 'YYYY/MM/DD') list($year, $month, $day) = explode('/', $mydate);
if ($format == 'YYYY.MM.DD') list($year, $month, $day) = explode('.', $mydate);
if ($format == 'DD-MM-YYYY') list($day, $month, $year) = explode('-', $mydate);
if ($format == 'DD/MM/YYYY') list($day, $month, $year) = explode('/', $mydate);
if ($format == 'DD.MM.YYYY') list($day, $month, $year) = explode('.', $mydate);
if ($format == 'MM-DD-YYYY') list($month, $day, $year) = explode('-', $mydate);
if ($format == 'MM/DD/YYYY') list($month, $day, $year) = explode('/', $mydate);
if ($format == 'MM.DD.YYYY') list($month, $day, $year) = explode('.', $mydate);
if (is_numeric($year) && is_numeric($month) && is_numeric($day))
return checkdate($month,$day,$year);
return false;
}

REGEX should be a last resort. PHP has a few functions that will validate for you. In your case, checkdate is the best option. http://php.net/manual/en/function.checkdate.php

Nicolas solution is best. If you want in regex,
try this,
this will validate for, 01/01/1900 through 12/31/2099 Matches invalid dates such as February 31st Accepts dashes, spaces, forward slashes and dots as date separators
(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)[0-9]{2}

This function working well,
function validateDate($date, $format = 'm/d/Y'){
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) === $date;
}

I know this is an older post, but I've developed the following function for validating a date:
function IsDateTime($aDateTime) {
try {
$fTime = new DateTime($aDateTime);
$fTime->format('m/d/Y H:i:s');
return true;
}
catch (Exception $e) {
return false;
}
}

Try This
/^(19[0-9]{2}|2[0-9]{3})\-(0[1-9]|1[0-2])\-(0[1-9]|1[0-9]|2[0-9]|3[0-1])((T|\s)(0[0-9]{1}|1[0-9]{1}|2[0-3]{1})\:(0[0-9]{1}|1[0-9]{1}|2[0-9]{1}|3[0-9]{1}|4[0-9]{1}|5[0-9]{1})\:(0[0-9]{1}|1[0-9]{1}|2[0-9]{1}|3[0-9]{1}|4[0-9]{1}|5[0-9]{1})((\+|\.)[\d+]{4,8})?)?$/
this regular expression valid for :
2017-01-01T00:00:00+0000
2017-01-01 00:00:00+00:00
2017-01-01T00:00:00+00:00
2017-01-01 00:00:00+0000
2017-01-01
Remember that this will be cover all case of date and date time with (-) character

Not sure if this answer the question or going to help....
$dt = '6/26/1970' ; // or // '6.26.1970' ;
$dt = preg_replace("([.]+)", "/", $dt);
$test_arr = explode('/', $dt);
if (checkdate($test_arr[0], $test_arr[1], $test_arr[2]) && preg_match("/[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}/", $dt))
{ echo(date('Y-m-d', strtotime("$dt")) . "<br>"); }
else
{ echo "no good...format must be in mm/dd/yyyy"; }

We can use simple "date" input type, like below:
Birth date: <input type="date" name="userBirthDate" /><br />
Then we can link DateTime interface with built-in function 'explode':
public function validateDate()
{
$validateFlag = true;
$convertBirthDate = DateTime::createFromFormat('Y-m-d', $this->birthDate);
$birthDateErrors = DateTime::getLastErrors();
if ($birthDateErrors['warning_count'] + $birthDateErrors['error_count'] > 0)
{
$_SESSION['wrongDateFormat'] = "The date format is wrong.";
}
else
{
$testBirthDate = explode('-', $this->birthDate);
if ($testBirthDate[0] < 1900)
{
$validateFlag = false;
$_SESSION['wrongDateYear'] = "We suspect that you did not born before XX century.";
}
}
return $validateFlag;
}
I tested it on Google Chrome and IE, everything works correctly. Furthemore, Chrome display simple additional interface. If you don't write anything in input or write it in bad format (correctly is following: '1919-12-23'), you will get the first statement. If you write everything in good format, but you type wrong date (I assumed that nobody could born before XX century), your controller will send the second statement.

I think it will help somebody.
function isValidDate($thedate) {
$data = [
'separators' => array("/", "-", "."),
'date_array' => '',
'day_index' => '',
'year' => '',
'month' => '',
'day' => '',
'status' => false
];
// loop through to break down the date
foreach ($data['separators'] as $separator) {
$data['date_array'] = explode($separator, $thedate);
if (count($data['date_array']) == 3) {
$data['status'] = true;
break;
}
}
// err, if more than 4 character or not int
if ($data['status']) {
foreach ($data['date_array'] as $value) {
if (strlen($value) > 4 || !is_numeric($value)) {
$data['status'] = false;
break;
}
}
}
// get the year
if ($data['status']) {
if (strlen($data['date_array'][0]) == 4) {
$data['year'] = $data['date_array'][0];
$data['day_index'] = 2;
}elseif (strlen($data['date_array'][2]) == 4) {
$data['year'] = $data['date_array'][2];
$data['day_index'] = 0;
}else {
$data['status'] = false;
}
}
// get the month
if ($data['status']) {
if (strlen($data['date_array'][1]) == 2) {
$data['month'] = $data['date_array'][1];
}else {
$data['status'] = false;
}
}
// get the day
if ($data['status']) {
if (strlen($data['date_array'][$data['day_index']]) == 2) {
$data['day'] = $data['date_array'][$data['day_index']];
}else {
$data['status'] = false;
}
}
// finally validate date
if ($data['status']) {
return checkdate($data['month'] , $data['day'], $data['year']);
}
return false;
}

Related

check the date format that is it correct or not

i want to check the date format of the database value. I want to put a check in my code if the format of the date string is correct. If it is not correct then store the empty value.
$getTmpAfSite = DB::table('tmp_af_site')->orderBy('id','DESC')->get(['id','name','email','number','origin','destination','estimated_rate','make','model','year','running_condition','carrier_type','avail_date','lead_source','request_params','bats_id','submitted_on']);
foreach ($getTmpAfSite as $key => $value) {
$avail_date = ($value->avail_date != '' && $value->avail_date == Carbon::parse($value->submitted_on)->format('m/d/Y')) ? Carbon::createFromFormat('m/d/Y', $value->avail_date)->format('Y-m-d') : '0000-00-00';
$submitted_on = ($value->submitted_on != '' && $value->submitted_on == Carbon::parse($value->submitted_on)->format('m/d/Y H:i')) ? Carbon::createFromFormat('m/d/Y H:i', $value->submitted_on)->format('Y-m-d H:i') : '0000-00-00 00:00:00';
DB::table('tmp_af_site')->where('id', $value->id)->update([
'avail_date'=>$avail_date,
'submitted_on'=>$submitted_on
]);
}
i am trying this code to check the value but its not working for me. If i didn't put a check on it and the wrong format comes then the error happens. Here is the error
Unexpected data found. Data missing
try use this function, this function check valid or not valid string date with return true false
function validateDate($date, $format = 'd-M-Y')
{
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) === $date;
}
if you want more format date, you can add checking date like this
function validateDate($date)
{
$valid = 0;
$format1 = 'Y-m-d';
$d = DateTime::createFromFormat($format1, $date);
if($d && $d->format($format) === $date){
$valid = 1;
}
$format2 = 'd-m-Y';
$d = DateTime::createFromFormat($format2, $date);
if($d && $d->format($format2) === $date){
$valid = 1;
}
return $valid;
}
You can use :
checkdate(int $month, int $day, int $year): bool
Example :
<?php
var_dump(checkdate(12, 31, 2000));
var_dump(checkdate(2, 29, 2001));
#bool(true)
#bool(false)
$valid = checkdate(12,31,2000);
if ($valid)
echo "Date is valid.";
else
echo "Date is not valid.";
?>
Regards,

Retrieve date format and parse if needed in PHP

I've created this function when retrieving a date from database and echo in Italian format to screen:
function get_data_ita($date) {
if ($date == "")
return "";
$d = new DateTime($date);
return $d->format('d/m/Y');
}
where $date is mysql format like: 2017-12-31 14:00:00
Now, if I pass a correct format like: 2017-12-31 14:00:00 the function works.
But sometimes I need to use the SAME function, passing an already formatted date like: 30/12/2017. In this case, i get parsing error of course.
How can I check if date passed is already in Italian format, and if yes return the untouched date, if not, parse the date?
I need a function like:
function get_data_ita($date) {
if ( $date== ALREADY_IN_ITALIAN_FORMAT )
return $date;
if ($date == "")
return "";
$d = new DateTime($date);
return $d->format('d/m/Y');
}
echo get_data_ita("30/12/2017");
echo get_data_ita("2017-12-31 14:00:00");
ECHO:
30/12/2017
31/12/2017
UPDATE: I found solution myself:
function validateDate($date, $format = 'Y-m-d')
{
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) == $date;
}
function get_data_ita($datetime_db) {
if ( validateDate($datetime_db, 'd/m/Y') ) {
return $datetime_db;
}
if ($datetime_db == "")
return "";
$date = new DateTime($datetime_db);
return $date->format('d/m/Y');
}
Replace / to -
<?php
function get_data_ita($date) {
if ($date == ""){
return "";
}
$date = str_replace('/','-',$date);
$d = new DateTime($date);
return $d->format('d/m/Y');
}
echo get_data_ita("30/12/2017");
echo "\n";
echo get_data_ita("2017-12-31 14:00:00");
?>
Check demo : https://eval.in/918149
Strtotime returns false if the date is not a valid date format.
This works for your inputs but not if there are other date formats.
function get_data_ita($date) {
if ($date == "") return "";
If(strtotime($date) !== False){
$d = new DateTime($date);
}Else{
$d = DateTime::createFromFormat('d/m/Y', $date);
}
return $d->format('d/m/Y');
}
echo get_data_ita("30/12/2017");
echo get_data_ita("2017-12-31 14:00:00");
https://3v4l.org/kt5Vg

Check if 2 given dates are a weekend using PHP

I have 2 dates like this YYYY-mm-dd and I would like to check if these 2 dates are a weekend.
I have this code but it only tests 1 date and I don't know how to adapt it; I need to add a $date_end.
$date = '2011-01-01';
$timestamp = strtotime($date);
$weekday= date("l", $timestamp );
$normalized_weekday = strtolower($weekday);
echo $normalized_weekday ;
if (($normalized_weekday == "saturday") || ($normalized_weekday == "sunday")) {
echo "true";
} else {
echo "false";
}
A couple of hints:
date('N') gives you normalised week day you can test against (no need to use localised strings)
Wrap it all in a custom function and you're done
You can use shorter code to check for weekend => date('N', strtotime($date)) >= 6.
So, to check for 2 dates — and not just 1 — use a function to keep your code simple and clean:
$date1 = '2011-01-01' ;
$date2 = '2017-05-26';
if ( check_if_weekend($date1) && check_if_weekend($date2) ) {
echo 'yes. both are weekends' ;
} else if ( check_if_weekend($date1) || check_if_weekend($date2) ) {
echo 'no. only one date is a weekend.' ;
} else {
echo 'no. neither are weekends.' ;
}
function check_if_weekend($date) {
return (date('N', strtotime($date)) >= 6);
}
Using your existing code, which is slightly longer, following is how you would check for 2 dates:
$date1 = '2011-01-01' ;
$date2 = '2017-05-27';
if ( check_if_weekend_long($date1) && check_if_weekend_long($date2) ) {
echo 'yes. both are weekends' ;
} else if ( check_if_weekend_long($date1) || check_if_weekend_long($date2) ) {
echo 'no. only one date is a weekend.' ;
} else {
echo 'no. neither are weekends.' ;
}
function check_if_weekend_long($date_str) {
$timestamp = strtotime($date_str);
$weekday= date("l", $timestamp );
$normalized_weekday = strtolower($weekday);
//echo $normalized_weekday ;
if (($normalized_weekday == "saturday") || ($normalized_weekday == "sunday")) {
return true;
} else {
return false;
}
}
Merging multiple answers into one and giving a bit extra, you'd come to the following:
function isWeekend($date) {
return (new DateTime($date))->format("N") > 5 ? true : false;
}
Or the long way:
function isWeekend($date) {
if ((new DateTime($date))->format("N") > 5) {
return true;
}
return false;
}
You can use the strtotime(); and date() functions to get the day of the date, and then check if is sat o sun
function check_if_weekend($date){
$timestamp = strtotime($date);
$day = date('D', $timestamp);
if(in_array($day, array('sun', 'sat'))
return true;
else return false;
}

unable to validate date

i am trying to validate date which is in between 1996 & 1900 for date of birth field. And also it should be in correct date format
but this below function is giving me output always false.
what i am doing wrong ?
function validateDate($date) {
$this->load->helper('date');
$datestring1 = "%Y-%m-%d";
$date1 = "1996-01-01";
$date2 = "1990-01-01";
$d = DateTime::createFromFormat('Y-m-d', $date);
return $d && $d->format('Y-m-d') == $date && $date > $date2 && $date < $date1;
}
I don't know what is wrong with your function but this should work
function validate($date){
$d = DateTime::createFromFormat('Y-m-d', $date);
if($d === false) return false;
$y = intval($d->format('Y'));
return $y >= 1990 && $y < 1996;
}
If you want 1988-07-25 to be a valid entry (as shown in your screenshot), your "date2" should be "1980" or something earlier instead of "1990".
You can try this
function validation($date){ //yyyy-mm-dd
$date_element = explode('-', $date);
if(is_array($date_element) and isset($date_element[0]) and ($date_element[0] >= 1990 and $date_element[0] <= 1996)){
return true;
}
return false;
}

Validate date format in php

I'm trying to validate date using PHP.
I'd like following formats to be valid:
d/m/yy
d/m/yyyy
dd/m/yy
dd/m/yyyy
d/mm/yy
d/mm/yyyy
dd/mm/yy
dd/mm/yyyy
I've tried many regular expressions and different variations of checkdate() function. Currently I have something like this:
function _date_is_valid($str)
{
if(strlen($str) == 0)
return TRUE;
if(substr_count($str,'/') == 2)
{
if (preg_match("/^((((31\/(0?[13578]|1[02]))|((29|30)\/(0?[1,3-9]|1[0-2])))\/(1[6-9]|[2-9]\d)?\d{2})|(29\/0?2\/(((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))|(0?[1-9]|1\d|2[0-8])\/((0?[1-9])|(1[0-2]))\/((1[6-9]|[2-9]\d)?\d{2}))/", $str))
{
$datearray = explode('/',$str);
if($datearray[2] > 2030)
return FALSE;
return checkdate($datearray[1], $datearray[0], $datearray[2]);
}
else
{
return FALSE;
}
}
return FALSE;
}
This however, validates dates like 11/11/200 and 11/11/200#
How can I validate date to match required format?
Edit: I could check datearray[2] to be between 10 and 30 and 2010 and 2030. But is there a way to check it using regex?
Edit1: return TRUE on strlen($str) == 0 is because I want users to be able to add events without knowing when will the event occur so someone else can qualify the schedule and assign event to certain date later
Just for the record. I ended up doing:
function _date_is_valid($str)
{
if(strlen($str) == 0) //To accept entries without a date
return TRUE;
if(substr_count($str,'/') == 2)
{
list($d,$m,$y) = explode('/',$str);
if(($y >= 10 && $y <= 30) || ($y >= 2010 && $y <= 2030))
{
return checkdate($m,$d,$y);
}
}
return FALSE;
}
Thanks for all your answers
function _date_is_valid($str) {
if (substr_count($str, '/') == 2) {
list($d, $m, $y) = explode('/', $str);
return checkdate($m, $d, sprintf('%04u', $y));
}
return false;
}
If it will always will be date / month / year you can use checkdate:
function _date_is_valid($str)
{
$array = explode('/', $str);
$day = $array[0];
$month = $array[1];
$year = $array[2];
$isDateValid = checkdate($month, $day, $year);
return $isDateValid;
}
an easy way to do this
<?php
if(!$formated_date = date_create_from_format('Y-m-d',$dateVar))
Try this:
function _date_is_valid($str) {
if (strlen($str) == 0) {
return TRUE;
}
return preg_match('/^(\d{1,2})\/(\d{1,2})\/((?:\d{2}){1,2})$/', $str, $match) && checkdate($match[2], $match[1], $match[3]) && $match[2] <= 2030;
}
I have been just changing the martin answer above, which will validate any type of date and return in the format you like.
Just change the format by editing below line of script strftime("10-10-2012", strtotime($dt));
<?php
echo is_date("13/04/10");
function is_date( $str )
{
$flag = strpos($str, '/');
if(intval($flag)<=0){
$stamp = strtotime( $str );
}else {
list($d, $m, $y) = explode('/', $str);
$stamp = strtotime("$d-$m-$y");
}
//var_dump($stamp) ;
if (!is_numeric($stamp))
{
//echo "ho" ;
return "not a date" ;
}
$month = date( 'n', $stamp ); // use n to get date in correct format
$day = date( 'd', $stamp );
$year = date( 'Y', $stamp );
if (checkdate($month, $day, $year))
{
$dt = "$year-$month-$day" ;
return strftime("%d-%b-%Y", strtotime($dt));
//return TRUE;
}else {
return "not a date" ;
}
}
?>
What I did to validate it was simple
function dateValidate($pDate) {
if(empty($pDate))
return true;
$chDate = date('Y-m-d', strtotime($pDate));
if($chDate != '1970-01-01')
return true;
else
return false;
}
You can find it out with using regexp too
how about if(strtotime($str) !== FALSE) $valid = TRUE;

Categories