unable to validate date - php

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

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 a date between two dates - PHP

I want to check a certain date that is stored in my DB, if this date is during this fiscal year it prints valid if it is not it prints invalid
here is my php code:
$init_date= date("2016/07/01");
$end_date= date("2017/06/30");
$i_date = strtotime($init_date);
$e_date = strtotime($end_date);
$date_db= strtotime($date);// this $date is retrieved from my DB
if ($e_date > $date_db && $i_date < $date_db)
{ echo "valid";}
else { echo "invalid";}
but the problem is that i don't want to set the start and the end dates manually, is there a way to make it dynamic? as it will be updated every year
This way your script will be a bit more dynamic.
// the below snippet checks the date retrieved from database
// against fiscal periods between years 2000 and 2050 and return the
// valid dates
$endYear=2000;
while($endYear<=2050) {
$end = $endYear.'/06/30';
$endDate = DateTime::createFromFormat('Y/m/d', $end);
$initDate = DateTime::createFromFormat('Y/m/d', $end);
$initDate = $initDate->sub(new DateInterval('P1Y'))->add(new DateInterval('P1D'));
$ddb = '2016-09-27';
$dateFrodDB = DateTime::createFromFormat('Y-m-d', $ddb);
if ($dateFrodDB>=$initDate && $dateFrodDB<=$endDate)
{ echo "valid\n";
echo "\tStartDate->\"".$initDate->format("Y-m-d")."\"\n";
echo "\tEndDate->\"".$endDate->format("Y-m-d")."\"\n";
echo "\tDateFromDatabase->\"".$dateFrodDB->format("Y-m-d")."\"\n";
}
$endYear++;
}
/* output
valid
StartDate->"2016-07-01"
EndDate->"2017-06-30"
DateFromDatabase->"2016-09-27"
*/
check this on PHP Sandbox
Try this,
<?php
$start_date = date('Y-m-d', strtotime(str_replace("/", "-", $initdate)));
$end_date = date('Y-m-d', strtotime(str_replace("/", "-", $end_date)));
$new_date = date('Y-m-d', strtotime(str_replace("/", "-", $date)));
if (($start_date < $new_date && $new_date < $end_date) || ($end_date < $new_date && $new_date < $start_date)) {
echo "valid";
} else {
echo 'invalid';
}
Here is working link

PHP add 1 month to date

I've a function that returns url of 1 month before.
I'd like to display current selected month, but I cannot use simple current month, cause when user clicks link to 1 month back selected month will change and will not be current.
So, function returns August 2012
How do I make little php script that adds 1 month to that?
so far I've:
<?php echo strip_tags(tribe_get_previous_month_text()); ?>
simple method:
$next_month = strtotime('august 2012 next month');
better method:
$d = new Date('August 2012');
$next_month = $d->add(new DateInterval('P1M'));
relevant docs: strtotime date dateinterval
there are 3 options/answers
$givendate is the given date (ex. 2016-01-20)
option 1:
$date1 = date('Y-m-d', strtotime($givendate. ' + 1 month'));
option 2:
$date2 = date('Y-m-d', strtotime($givendate. ' + 30 days'));
option 3:
$number = cal_days_in_month(CAL_GREGORIAN, date('m', strtotime($givendate)), date('Y', strtotime($givendate)));
$date3 = date('Y-m-d', strtotime($date2. ' + '.$number.' days'));
You can with the DateTime class and the DateTime::add() method:
Documentation
You can simple use the strtotime function on whatever input you have to arrive at April 2012 then apply the date and strtotime with an increment period of '+1 month'.
$x = strtotime($t);
$n = date("M Y",strtotime("+1 month",$x));
echo $n;
Here are the relevant sections from the PHP Handbook:
http://www.php.net/manual/en/function.date.php
https://secure.php.net/manual/en/function.strtotime.php
This solution solves the additional issue of incrementing any amount of time to a time value.
Hi In Addition to their answer. I think if you just want to get the next month based on the current date here's my solution.
$today = date("Y-m-01");
$sNextMonth = (int)date("m",strtotime($today." +1 months") );
Notice That i constantly define the day to 01 so that we're safe on getting the next month. if that is date("Y-m-d"); and the current day is 31 it will fail.
Hope this helps.
Date difference
$date1 = '2017-01-20';
$date2 = '2019-01-20';
$ts1 = strtotime($date1);
$ts2 = strtotime($date2);
$year1 = date('Y', $ts1);
$year2 = date('Y', $ts2);
$month1 = date('m', $ts1);
$month2 = date('m', $ts2);
echo $joining_months = (($year2 - $year1) * 12) + ($month2 - $month1);
Since we know that strtotime(+1 month) always adds 30 days it can be some troubles with dates ending with the day 31, 30 or 29 AND if you still want to stay within the last day of the next month.
So I wrote this over complicated script to solve that issue as well as adapting so that you can increase all type of formats like years, months, days, hours, minutes and seconds.
function seetime($datetime, $p = '+', $i, $m = 'M', $f = 'Y-m-d H:i:s')
{
/*
$datetime needs to be in format of YYYY-MM-DD HH:II:SS but hours, minutes and seconds are not required
$p can only be "+" to increse or "-" to decrese
$i is the amount you want to change
$m is the type you want to change
Allowed types:
Y = Year
M = Months
D = Days
W = Weeks
H = Hours
I = Minutes
S = Seconds
$f is the datetime format you want the result to be returned in
*/
$validator_y = substr($datetime,0,4);
$validator_m = substr($datetime,5,2);
$validator_d = substr($datetime,8,2);
if(checkdate($validator_m, $validator_d, $validator_y))
{
$datetime = date('Y-m-d H:i:s', strtotime($datetime));
#$p = either "+" to add or "-" to subtract
if($p == '+' || $p == '-')
{
if(is_int($i))
{
if($m == 'Y')
{
$year = date('Y', strtotime($datetime));
$rest = date('m-d H:i:s', strtotime($datetime));
if($p == '+')
{
$ret = $year + $i;
}
else
{
$ret = $year - $i;
}
$str = $ret.'-'.$rest;
return(date($f, strtotime($str)));
}
elseif($m == 'M')
{
$year = date('Y', strtotime($datetime));
$month = date('n', strtotime($datetime));
$rest = date('d H:i:s', strtotime($datetime));
$his = date('H:i:s', strtotime($datetime));
if($p == '+')
{
$ret = $month + $i;
$ret = sprintf("%02d",$ret);
}
else
{
$ret = $month - $i;
$ret = sprintf("%02d",$ret);
}
if($ret < 1)
{
$ret = $ret - $ret - $ret;
$years_back = floor(($ret + 12) / 12);
$monts_back = $ret % 12;
$year = $year - $years_back;
$month = 12 - $monts_back;
$month = sprintf("%02d",$month);
$new_date = $year.'-'.$month.'-'.$rest;
$ym = $year.'-'.$month;
$validator_y = substr($new_date,0,4);
$validator_m = substr($new_date,5,2);
$validator_d = substr($new_date,8,2);
if(checkdate($validator_m, $validator_d, $validator_y))
{
return (date($f, strtotime($new_date)));
}
else
{
$days = date('t',strtotime($ym));
$new_date = $ym.'-'.$days.' '.$his;
return (date($f, strtotime($new_date)));
}
}
if($ret > 12)
{
$years_forw = floor($ret / 12);
$monts_forw = $ret % 12;
$year = $year + $years_forw;
$month = sprintf("%02d",$monts_forw);
$new_date = $year.'-'.$month.'-'.$rest;
$ym = $year.'-'.$month;
$validator_y = substr($new_date,0,4);
$validator_m = substr($new_date,5,2);
$validator_d = substr($new_date,8,2);
if(checkdate($validator_m, $validator_d, $validator_y))
{
return (date($f, strtotime($new_date)));
}
else
{
$days = date('t',strtotime($ym));
$new_date = $ym.'-'.$days.' '.$his;
return (date($f, strtotime($new_date)));
}
}
else
{
$ym = $year.'-'.$month;
$new_date = $year.'-'.$ret.'-'.$rest;
$validator_y = substr($new_date,0,4);
$validator_m = substr($new_date,5,2);
$validator_d = substr($new_date,8,2);
if(checkdate($validator_m, $validator_d, $validator_y))
{
return (date($f, strtotime($new_date)));
}
else
{
$ym = $validator_y . '-'.$validator_m;
$days = date('t',strtotime($ym));
$new_date = $ym.'-'.$days.' '.$his;
return (date($f, strtotime($new_date)));
}
}
}
elseif($m == 'D')
{
return (date($f, strtotime($datetime.' '.$p.$i.' days')));
}
elseif($m == 'W')
{
return (date($f, strtotime($datetime.' '.$p.$i.' weeks')));
}
elseif($m == 'H')
{
return (date($f, strtotime($datetime.' '.$p.$i.' hours')));
}
elseif($m == 'I')
{
return (date($f, strtotime($datetime.' '.$p.$i.' minutes')));
}
elseif($m == 'S')
{
return (date($f, strtotime($datetime.' '.$p.$i.' seconds')));
}
else
{
return 'Fourth parameter can only be any of following: Valid Time Parameters Are: Y M D Q H I S';
}
}
else
{
return 'Third parameter can only be a number (whole number)';
}
}
else
{
return 'Second parameter can only be + to add or - to subtract';
}
}
else
{
return 'Date is not a valid date';
}
}

php date validation

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

Categories