How to check string on date in laravel?
I want to handle the situation if string doesn't date for example like "it's some not date string".
I try it code, but it doesn't work I have next error:
InvalidArgumentException : A two digit month could not be found
Data missing
My code:
if (Carbon::createFromFormat('m-d-Y', $rowMatrix[4]) !== false) {
//
}
You can use DateTime for this purpose :
$dateTime = DateTime::createFromFormat('d/m/Y', $rowMatrix[4]);
$errors = DateTime::getLastErrors();
if (!empty($errors['warning_count'])) {
// Not a date
}
Or you can check it like this :
if (date('Y-m-d H:i:s', strtotime($rowMatrix[4])) == $rowMatrix[4]){
// it's a date
}
You can use try/catch block:
try {
$date = Carbon::createFromFormat('m-d-Y', $rowMatrix[4])
} catch(InvalidArgumentException $e) {
$date = 'Not a date';
}
But a much better way is to use Laravel validation date_format rule to make sure the string is a date:
'some_date_field' => 'date_format:"m-d-Y"',
Related
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
I've a varible passed as String on a php method in a Symofny2 Application:
public function eventAllByScenarioAndDateAction($apiVersion, $scenario,$date, $options)
then the $date must be a DateTime type in format YYYY-MM-DD HH:MM:SS to passing it for populating a table by using a sql query.
I'd like to check if the format passed is correct so i put the control:
$dateControl1=strtotime($date);
and then the if sentence:
if ($dateControl1 === false)
but the "if" is setted to false just if I send something like 2013-33-01 and not for example if i cut the HH:MM:SS
so how can I check how the $date is passed to the method and for example having different behavior if I have only YYYY-MM-DD (but correct) or the whole YYYY-MM-DD HH:MM:SS
Again, how can I discard format different from the expected one (for example with / instead of - etc.)
There is no need to be that specific. The following works just fine:
$foo = new DateTime("2013-01-01");
$bar = new DateTime("2013-01-01 01:23:45");
echo $foo->format("Y-m-d H:i:s"); // 2013-01-01 00:00:00
echo $bar->format("Y-m-d H:i:s"); //2013-01-01 01:23:45
If an invalid date is your main concern, us a try/catch clause:
try {
$baz = new DateTime("foobar");
} catch (Exception $e) {
// do something else here
// like throwing an HTTP Exception
}
Actually the #nietonfir solution works fine for me:
try { $dateNew = new \DateTime('$date'); } catch (\Exception $e) { echo return $e; }
(note the "\" before some declaration for bypassing symofny exception)
Because if someone passing just YYYY-mm-dd the date is completed by 00:00:00 hour
But what I'd like to do is to checkin what is $date before validate it!
So for example
SOMETHING THAT CHECKIN DATE IF ITS yyyy-mm-dd `hh:mm:ss OR just yyyy-mm-dd
and THEN IF WE ARE IN THE SECOND CASE DOING SOMETHING BEFORE doing
try { $dateNew = new \DateTime('$date'); } catch (\Exception $e) { echo return $e; }
Approach like:
list($date1, $time) = explode(" ",$date);
doesn't works because the space " " isn't recognized if we are in yyyy-mm-dd case and it raise an exception like:
Notice: Undefined offset: 1 in...........
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;
}
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.
Now I sq use the DateTime class to convert to different time formats and I find it very useful except one feature. Before when the user try to add date but for some reason skip the time I got 00:00:00 for the time which was good enough for me. Now, with the DateTime class if the time is not included it return error.
Here is my code:
$dt = DateTime::createFromFormat("d.m.Y H:i:s", $data['event_time']);
if($dt === false)
{
throw new Exception("Invalid date");
}
$formattedDate = $dt->format('Y-m-d H:i:s');
Every time I try to insert date without time I get Invalid date error. Is there a way to insert zeros on the place of the time, except getting error for this?
Thanks
Leron
Some simple pre-validation:
$date['event_time'] = trim($date['event_time']);
if (preg_match('/^\d{2}\.\d{2}\.\d{4}$/', $date['event_time'])) {
$date['event_time'] .= ' 00:00:00';
} else if (!preg_match('/^\d{2}\.\d{2}\.\d{4} \d{2}:\d{2}:\d{2}$/', $date['event_time'])) {
die('Invalid format');
}
If you don't want to use regex I guess this should work too. If i was you I would use #deceze solution instead of this :P but for the sake of completeness, here it is:
$dt = DateTime::createFromFormat("d.m.Y H:i:s", $data['event_time']);
if($dt === false)
{
$data['event_time'] = trim($data['event_time']);
$data['event_time'] .= " 00:00:00";
$dt = DateTime::createFromFormat("d.m.Y H:i:s", $data['event_time')
if ($dt === false) {
throw new Exception("Invalid date");
}
}
$formattedDate = $dt->format('Y-m-d H:i:s');