Validating a date dd/mm/yyyy - php

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

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

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

Verifying Date/Time Input in PHP

New to programming in PHP. Trying to verify input format for a date/time. User input is as follows for Nov 27 2012 at 6 PM '2012-nov-27|6pm'.
Not really sure where to start. Any suggestions? Thanks.
Have a look here for date_parse_from_format documentation and here for general date formatting. Give this a try:
<?php
$date = "2012-nov-27|6pm";
print_r(date_parse_from_format("Y-M-d|ga", $date));
?>
Gangnam OOP style:
$input = '2012-nov-27|6pm';
$date = \DateTime::createFromFormat('Y-M-j ga', str_replace('|', ' ', $input));
if ($date === false) {
throw new \Exception('Invalid date!');
}
NOTE: I experienced an issue by using | in format/date string, so that the str_replace()
NOTE 2: If input day format is 01-31 instead of 1-31, replace the j with a d in createFromFormat() first parameter.
You can use checkdate:
if(checkdate($month, $day, $year)){
echo 'Valid date!';
}
Or, you can convert whatever the user enters with strtotime(). If strtotime can't determine what the date is, it returns bool false.
if(strtotime($dateEntered) !== false){
echo 'Valid date!';
}
Try:
$datetime = "2012-nov-27|6pm";
$unixtime = strtotime( $datetime );
if( is_numeric($unixtime) && $unixtime <= PHP_INT_MAX ) {
//do something if true
} else {
echo "Invalid DateTime";
}
Demo
If you're just looking to test your date for validity, the following will work. Even if you were just looking to test the input format, I suggest you also sanity check the data as well.
$thedate = "2012-nov-27|6pm";
$arryParts = explode("|", $thedate);
$arryDate = date_parse($arryParts[0]);
if(!checkdate($arryDate['month'], $arryDate['day'], $arryDate['year'])) {
/* error handling */
}
/* valid date, continue processing */
If you just want to check the format, use a regex:
$months = 'jan|feb|mar|apr|may|jun|jul|aug|sep|okt|nov|dec';
$pattern = '/([0-9]{4})-('.$months.')-([0-9]{2})\\|([0-9]?[0-9])(am|pm)/';
preg_match($pattern, $input, $matches);
var_dump($matches);
If you really want to check if a specific date/time exists, thing become more complicated. I may be wrong, but I don't think it can be done using PHP date functions, as they are quite tolerant to input errors. Maybe there's a library to do this.

php make date with format mm-dd-yyyy

I have a date in the following format
MM-DD-YYYY
How can I convert this to UNIX time in PHP
Thanks
Having a small problem
$date = strtotime($_POST['retDate']);
print $date; //Prints nothing
print $_POST['retDate']; //Prints 08-18-2009
If the format is always like that, I'd would try something like:
list($m,$d,$y) = explode('-', '08-18-2009');
$time = mktime(0, 0, 0, $m, $d, $y);
print date('m-d-Y', $time);
As for your example, the problem is the function fails. You should check it like so:
if(($time=strtotime('08-18-2009'))!==false)
{
// valid time format
}
else
echo 'You entered an invalid time format';
or you can use php date obyek to do that, like this
$tgl = "30-12-2013";
$tgl2 = DateTime::createFromFormat('d-m-Y', $tgl);
print_r($tgl2);
echo($tgl2->format('Y-m-d'));
i hope this can help...
Use strtotime:
$str = "03-31-2009";
$unixtime = strtotime($str);
Since these answers and comments were provided, PHP has updated to include a native function that suits this situation perfectly. Check out PHP's DateTime object here. This includes a createFromFormat method that will do as requested. In this particular example:
$date = DateTime::createFromFormat('j-M-Y', $_POST['retDate']);
From there, you can format it as desired or perform any other date operations:
echo $date->format('Y-m-d');
And that's it! Keep in mind that this is only provided in PHP 5.3.0 or higher!

Categories