Home > database >  check the date format that is it correct or not
check the date format that is it correct or not

Time:12-23

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

CodePudding user response:

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

CodePudding user response:

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)

Regards,

  • Related