date validation

Asked

Viewed 198 times

1

I am creating a validation class and I have a method to validate dates.
When will I validate based on now, strtotime calculates including time.

$v->rule( '07/28/2014' , 'before.2014' ) this rule validates only the year
$v->rule( '07/28/2014' , 'before.now' ) this rule validates the M.D.Y date

For the first case the comparison is:
strtotime( '2014' ) < strtotime( '2014' )

For the second case the comparison is:
strtotime( '07/28/2014' ) < strtotime( '07/28/2014 17:59:46' )

The result is a false and another true.
I might add H:i:s when comparing 07/28/2014, or using strtotime( date( 'm/d/Y' ) ) or another alternative to now.

In PHP you have the warning, about the now, but here the time is normal

In PHP 5 higher than 5.0.2, "now" and other relative time are erroneously computed for midnight of the day. Different from other versions where it is correctly computed from the current time.

  • A now only in Y-m-d I believe it is ideal. Another detail, avoid strtotime, use datetime whenever possible. http://answall.com/a/26749/4751

2 answers

1

A good option is to use the php 'Datetime' object http://php.net/manual/en/datetime.createfromformat.php

Example

$date = DateTime::createFromFormat('d/m/Y', '28/07/2014');

Note: This function is present from version 5.3 of PHP

Remember that when you omit the time it takes the current time

  • You saw the highlight in yellow in his post?

  • @Anderson Danilo, Vale lembrar que quando você omite o horário ele assume o horário atual what you said I said in the second line

1

You can use the function below:

$data = '01/02/2017';

function validaData($data, $formato = 'd/m/Y H:i:s'){

    $d = DateTime::createFromFormat($formato, $data);

    return $d && $d->format($formato) == $data;
}

if(validaData($data, 'd/m/Y')){
    echo 'Data válida';
}else{
    echo 'Data inválida';
}

//Return: Data válida

The interesting that you can inform the format that your date has to be, and can also validate time.

I hope I’ve helped!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.