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;
Related
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;
}
I am trying to find the date not less than 18 years, I tried this following code, but its not working for me.
// validate birthday
function validateAge($then, $min)
{
// $then will first be a string-date
$then = strtotime($then);
echo "<br>";
echo 'test1-';
var_dump( $then );
exit;
//The age to be over, over +18
$min = strtotime('+18 years', $then);
if(time() < $min) {
die('Not 18');
}
}
$res = validateAge('2016-02-29', $min = 18);
var_dump($res);
I fyou see the above question, you can see that, date is not valid, even if i pass the wrong date, its shows the $then = strtotime($then);
var_dump($then) show the int
my question is, how its printing the timestamp, event if we passing the invalid date.
Your logic is correct. Remove die, exit and echo which is not needed
function validateAge($then, $min)
{
// $then will first be a string-date
$then = strtotime($then);
//The age to be more then min years
$min = strtotime('+'. $min . ' years', $then);
return time() > $min;
}
$res = validateAge('2016-02-29', $min = 18);
echo $res ? 'O\'key' : "Not $min years";
demo
Try maybe something like this
function compareAge($date,$min=18)
{
$strdate = strtotime($date);
$curdate = strtotime("today");
$datefin=date("Ymd",$curdate)-date("Ymd",$strdate);
$age=substr($datefin,0,strlen($datefin)-4);
return $age>=$min;
}
var_dump(compareAge("2013-05-13"));
DEMO
you could use this method:
public function validateAge($then)
{
$then= date_create($then);
$now = date_create("now");
$diff = $now->diff($then);
if ($diff->y > 18)
{
die('not 18');
}
}
Duplicate:
Calculating number of years between 2 dates in PHP
use the datetime object to save all sorts of pain. Its so much more simple.
function validateAge(DateTime $then, $min = 18)
{
$now = new DateTime();
$minimum = clone($now); // you could just modify now, but this is simpler to explain
$minimum->modify("-$min years");
if($then < $minimum) {
return false;
}
return true;
}
echo validateAge(new DateTime('1-1-1997')) ? 'true' : 'false'; // returns false
echo validateAge(new DateTime('1-1-1999')) ? 'true' : 'false'; // returns true
see example
Wow, so many try-hards.
In case you like is simple:
<?php
function validateAge($date) {
return date_create('18 years ago') > date_create($date);
}
var_dump(
validateAge('2010-10-05'),
validateAge('1992-09-02')
);
OUTPUT
bool(false)
bool(true)
Play with me on 3v4l.org
Edit: Also works with the $min parameter:
<?php
function validateAge($date, $min) {
return date_create("$min years ago") > date_create($date);
}
var_dump(
validateAge('2010-10-05', 18),
validateAge('1992-09-02', 18)
);
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;
}
Example (Today is 13.05.2013):
11/05/2013,20/05/2013,9/05/2013 <-- false;
10/03/2013,14/04/2013,12/05/2013 <-- true;
15/06/2013,11/06/2013,8/06/2013 <-- false;
13/05/2013,10/04/2013,02/05/2013 <-- false (is today = false)
PHP :
function outdate($dates) {
$dates = str_replace('/','-',$dates);
$dates = explode(',',$dates);
$today = time();
foreach ($dates as $date) {
if($today > strtotime($date)) {
// ????
}
}
}
I have done with some parts. Please help me to do return true or false
I will use my function like..
if( outdate('11/05/2013, 12/05/2013, 9/05/2013') ) {
// do something
}
Anyone can help me ?
Suppose this is what you need:
function outdate($dates) {
$res = true;
$dates = str_replace('/','-',$dates);
$dates = explode(',',$dates);
$today = time();
foreach ($dates as $date) {
if($today < strtotime($date)) {
$res = false;
break;
}
}
return $res;
}
It will return true if all passed dates are in past. And false if at least one date is today or in future.
function outdate($dates) {
$flag = false;
$dates = str_replace('/','-',$dates);
$dates = explode(',',$dates);
$today = time();
foreach ($dates as $date) {
if($today > strtotime($date)) {
$flag = true;
break;
}
}
return $flag;
}
You can use an array instead, something like this (untested)
$array = array("11/05/2013", "12/05/2013", "9/05/2013");
$result = checkDates($array);
function checkDates($array)
{
foreach($array as $a)
{
$date = strtotime(preg_replace("/^([0-9]{1,2})[\/\. -]+([0-9]{1,2})[\/\. -]+([0-9]{1,4})/", "\\2/\\1/\\3", $a));
if($date>time()) return false;
}
return true;
}
I found my another to do.. Just find a max date first then check it!
function outdate($dates) {
$dates = str_replace('/','-',$dates);
$dates = explode(',',$dates);
$ts_dates = array();
foreach ($dates as $date) {
$ts_dates[] = strtotime($date);
}
$max_date = max($ts_dates);
$today = strtotime('today');
if($max_date < $today) {
return true;
} else {
return false;
}
}
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;
}