Check PHP datetime stamp is correct? - php

Is there a way of checking whether a date time stamp is correct in PHP?
I am currently using yyyy-mm-dd hh:mm:ss in MySQL and would like to ensure when a user provides the date/time stamp in a form it matches the correct format.

[until someone comes with good (bugfree), working checkdate() example ]
I am using this function:
<?php
function validateMysqlDate( $date ){
if (preg_match("/^(\d{4})-(\d{2})-(\d{2}) ([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/", $date, $matches)) {
if (checkdate($matches[2], $matches[3], $matches[1])) {
return true;
}
}
return false;
}
// check it:
$a = validateMysqlDate('2012-12-09 09:04:00');
$b = validateMysqlDate('20122-12-09 09:04:00');
$c = validateMysqlDate('2012-12_09 09:04:00');
$d = validateMysqlDate('');
var_dump( $a );
var_dump( $b );
var_dump( $c );
var_dump( $d );
?>
and btw: checkdate() would return true for $b although it is not a valid mysql datetime

You can use the checkdate() function to check the validity of a date.
http://php.net/manual/en/function.checkdate.php
You can also pass all of the parts of your timestamp to mktime() and if false or -1 is returned (depending on PHP version) then it's an invalid date
http://www.php.net/manual/en/function.mktime.php

This a duplicate question. For additiona discussion and answers see MySQL: How to check if a string is a valid DATE, TIME or DATETIME

Try to parse the given string and then check it is the same date that you entered, note the below:
$dt = DateTime::createFromFormat('Y-m-d H:i:s', '2011-01-32 12:00:00');
echo $dt->format('Y-m-d H:i:s');
// outputs 2011-02-01 12:00:00
HTH.

Related

How to force php strtotime to return today date if date variable is empty?

I have a js calendar in an HTML page and I'm passing the picked date into a PHP file. Currently, the date field is mandatory and it will display the default 1970/01/01 if no date is picked in the calendar.
I'm trying to change the behavior so that when no date is picked, then the current date will be passed into the PHP file.
The code in the PHP file is the one below:
$mydate = strtotime($_POST['mydate']);
$mydate = date("Y/m/d",$mydate);
How can I change it in order to display the current date if there's no value passed from $_POST['mydate']?
PS: I'm a newbie to PHP functions and searching for similar cases in the forums did not help.
The reason you get that is because strtotime returns false if it can't parse the date.
False is typecasted to 0, and date of 0 is 1970.
What you can do is to check if the strtotime return is false. (Not the same as isset or 0 in my opinion).
$mydate = strtotime($_POST['mydate']);
if($mydate === false){ // === is strict comparison
$mydate = date("Y/m/d");
}else{
$mydate = date("Y/m/d",$mydate);
}
Try this:
if( empty( $_POST['mydate'])){
$mydate = date("Y/m/d");
} elseif( FALSE !== $tm = strtotime( $_POST['mydate'])) {
$mydate = date("Y/m/d", $tm);
} else {
$mydate = date("Y/m/d");
}

Call to a member function format() on boolean

I want to find the difference between two dates and I have used date_diff for the same. When format function is applied on date_diff object it returns an error.
Call to a member function format() on boolean
$field_value is fetched from the database and it's format is dd/mm/YYYY. When I hard-code the values for $field_value and $indexing_value the following code works.
Everything is running fine till line number 8. I have tried outputting the value of
$diff->format("%R%a")
and it is returning exact value but the code gives error near the if statement.
$date = new DateTime();
$current_date = $date->format('d/m/Y');
$indexing_value = str_replace("/", "-", $field_value);
$current_value = str_replace("/", "-", $current_date);
$indexing_value = date_create($indexing_value);
$current_value = date_create($current_value);
$diff = date_diff($indexing_value, $current_value);
if ($diff->format("%R%a") < 0) {
echo "1";
} else {
echo "2";
}
Please let me know what is wrong with the above code.
add condition to check whether you got the diff or not, as it returns false if there is error . Check manual for the same
$diff = date_diff($indexing_value, $current_value);
if ($diff) {
if ($diff->format("%R%a") < 0) {
echo "1";
}else{
echo "2";
}
}
You are getting error because for some values the diff is not calculated and have value False in $diff
Please let me know what is wrong with the above code.
There are several issues with the code:
You don't check the values returned by date_create(); it returns FALSE on error.
What's the point of formatting $date then creating $current_value back from the resulting string? If you don't care about the time components and need to use only the date part of a DateTime object you can use its setTime() method to set the time components to 0.
What's the point of using str_replace() to manipulate the text representation of a date when you know its format? DateTime::createFromFormat() can be used to parse the string into a DateTime object.
There is no need to compute the difference of the two dates and the format it and compare the value to 0. The DateTime objects can be compared directly.
All in all, all the code you need is:
// Current date & time
$today = new DateTime();
// Ignore the time (change $today to "today at midnight")
$today->setTime(0, 0, 0);
// Parse the value retrieved from the database
$field = DateTime::createFromFormat('d/m/Y', $field_value);
// We don't care about the time components of $field either (because the time
// is not provided in the input string it is created using the current time)
$field->setTime(0, 0, 0);
// Directly compare the DateTime objects to see which date is before the other
if ($field < $today) {
echo "1";
} else {
echo "2";
}

Check if I'm passing only a date without time

Is there a way on PHP I can check if I'm posting only a date without a time?
Ex.
2015-11-18 -> TRUE
2015-11-18 00:00:00 -> FALSE
2015-11-18 23:59:00 -> FALSE
Thank you!
To get the current date you can use-
date("Y-m-d")
It gives only the date.
or if you already have a date -
$date = '10.21.2011';
echo date('Y-m-d', strtotime(str_replace('.', '/', $date)));
to validate you can use preg_match-
$date="10.21.2011";
if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/",$date))
{
return true;
}else{
return false;
}
$date = "2014-04-01 12:00:00";
preg_match('/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/',$date);
function.checkdate
You can use my function (or on PHP.net) to validate date&time for this purpose:
var_dump( validateDate('2015-11-18', 'Y-m-d') ); # true
var_dump( validateDate('2015-11-18 00:00:00', 'Y-m-d') ); # false
var_dump( validateDate('2015-11-18 23:59:00', 'Y-m-d') ); # false
demo
This can be done in a simple way .
What I have done is , I split the string into an array .
As all the 3 strings (Date sample given by you),differentiates from each other by : symbol. So Split it and use count() method.if its split then count() will return value > 1 .That's it in a simple way..
<?php
//U can use $a=date("Y-m-d");
$a='2015-11-18'; //Here i am taking an Example
$b=explode(':' , $a);
if(count($b)>1)
{
echo "FALSE";
}else
{
echo "TRUE";
}
Hope You were expecting something like this .
Note- I have answered as per your question.For general case it will be
different.

strtotime() converts a non existing date to another date

I am building a timestamp from the date, month and year values entered by users.
Suppose that the user inputs some wrong values and the date is "31-02-2012" which does not exist, then I have to get a false return. But here its converting it to another date nearby. Precisely to: "02-03-2012"..
I dont want this to happen..
$str = "31-02-2012";
echo date("d-m-Y",strtotime($str)); // Outputs 02-03-2012
Can anyone help? I dont want a timestamp to be returned if the date is not original.
You might look into checkdate.
That's because strtotime() has troubles with - since they are used to denote phrase like -1 week, etc...
Try
$str = '31-02-2012';
echo date('d-m-Y', strtotime(str_replace('-', '/', $str)));
However 31-02-2012 is not a valid English format, it should be 02-31-2012.
If you have PHP >= 5.3, you can use createFromFormat:
$str = '31-02-2012';
$d = DateTime::createFromFormat('d-m-Y', $str);
echo $d->format('d-m-Y');
You'll have to check if the date is possible before using strtotime. Strtotime will convert it to unix date meaning it will use seconds since... This means it will always be a date.
You can workaround this behavior
<?php
$str = "31-02-2012";
$unix = strtotime($str);
echo date('d-m-Y', $unix);
if (date('d-m-Y', $unix) != $str){
echo "wrong";
}
else{
echo date("d-m-Y", $unx);
}
or just use checkdate()
Use the checkdate function.
$str = "31-02-2012";
$years = explode("-", $str);
$valid_date = checkdate($years[1], $years[0], $years[2]);
Checkdate Function - PHP Manual & Explode Function - PHP Manual
Combine date_parse and checkdate to check if it's a valid time.
<?php
date_default_timezone_set('America/Chicago');
function is_valid_date($str) {
$date = date_parse($str);
return checkdate($date['month'], $date['day'], $date['year']);
}
print is_valid_date('31-02-2012') ? 'Yes' : 'No';
print "\n";
print is_valid_date('28-02-2012') ? 'Yes' : 'No';
print "\n";
Even though that date format is acceptable according to PHP date formats, it may still cause issues for date parsers because it's easy to confuse the month and day. For example, 02-03-2012, it's hard to tell if 02 is the month or the day. It's better to use the other more specific date parser examples here to first parse the date then check it with checkdate.

Problem with short date format in php

I have problem with date function in php. If I supply string in format "d.m.y" for example "01.01.01" it gets rendered as todays date which means that php gets confused.
I found:
Note:
The "Day, month and two digit year, with dots or tabs" format (dd [.\t] mm "." yy)
only works for the year values 61 (inclusive) to 99
(inclusive) - outside those years the time format "HH [.:] MM [.:] SS" has
precedence.
on: php.net site
How to override this behavior?
I know of date_create_from_format function which would work fine if I knew input will always be in format "d.m.y", but it won't.
UPDATE 1:
Code
$date = new DateTime('01.01.01');
echo $date->format('Y-m-d');
outputs 2010-10-19 and I wanted 2001-01-01.
To format a date other than now, use the second parameter. For example:
echo date("d.m.y", 1255982665);
echoes 19.10.09
Just read the documentation! PHP's site is excellent
It seems like you want to reformat a date?
mktime() gives unix timestamp from component pieces
date() gives string from unixtimestamp (or implied now)
getdate() gives assoc array from unix timestamp
I think you want -
$arr = explode($dateIn, ':'); //get array [day, month, year]
$timestamp = mktime(0,0,0, $arr[0], $arr[1], $arr[2]) //unix time stamp, a long integer representing time
date(DESIREDFORMAT, $timestamp);
check out the output formats here - http://us2.php.net/manual/en/function.date.php
function getDateFromString( $str )
{
$date = DateTime::createFromFormat( 'd.m.y', $str );
if ( $date !== false )
return $date->getTimestamp();
// you can try other common formats here
// ...
// otherwise just parse whatever there is
return strtotime( $str );
}
echo date( 'd.m.Y H:i', getDateFromString( '01.01.01' ) ); // 01.01.2001 20:14
Edit
To adjust it a bit more to get your exact output:
function getDateTimeFromString( $str )
{
$date = DateTime::createFromFormat( 'd.m.y', $str );
if ( $date !== false )
return $date;
// you can try other common formats here
// ...
// otherwise just parse whatever there is
return new DateTime( $str );
}
$date = getDateTimeFromString( '01.01.01' );
echo $date->format( 'Y-m-d' ); // 2001-01-01

Categories