Check if I'm passing only a date without time - php

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.

Related

What is the easiest way to check if time is set in datetime variable

I have function one of the arguments of which is $date variable.
Sometimes there is time in the date (like 2018-01-01 15:40:43),
sometimes - there is not (like 2018-01-01).
I want to know if time is set.
What is the easiest way to do it?
Here is what I tryied:
function checkDate ($date) {
$time = date("H:i:s", strtotime($date));
if ($time == '00:00:00') {
//time was not set!
}
}
Obviously, this works, but untill something like 2018-06-01 00:00:00 is passed.
I would not like using explode of string if there is some other solution.
Thank you/.
I think you can use date_parse
check this: http://php.net/manual/en/function.date-parse.php
you can check for the minutes, hours and seconds from the resulting array :D
also you can check for errors in date.
You can use the Datetime class to test. What the code below will do is attempt to create a Datetime object from a date as long as it is in the format that is specified.
So if you pass anything other than a date that is in the time format that you specify it will error. Then you use the getLastErrors() to check.
Like so:
function checkIsDate($date){
$date = DateTime::createFromFormat('Y-m-d', $date);
$date_errors = DateTime::getLastErrors();
if ($date_errors['warning_count'] + $date_errors['error_count'] == 0) {
return TRUE;
} else {
return FALSE;
}
}
echo checkIsDate('2018-05-29')?'True':'False'; //<-- Will return true;
echo checkIsDate('2018-05-29 11:30:00')?'True':'False'; //<-- Will return false;
echo checkIsDate('05/29/2018')?'True':'False'; //<-- Will return false;
For completeness, here's a plain string functions version:
$input = [
'2018-01-01',
'2018-01-01 15:40:43',
'2018-01-01 00:00:00',
];
foreach ($input as $string) {
list($year, $month, $day, $hour, $minutes, $seconds) = array_pad(preg_split('/[^\\d]+/i', $string, -1, PREG_SPLIT_NO_EMPTY), 6, null);
printf("%s has time? %s\n", $string, $hour!==null ? 'Yes' : 'No');
}
2018-01-01 has time? No
2018-01-01 15:40:43 has time? Yes
2018-01-01 00:00:00 has time? Yes
Tweak checks to your liking.
I would not recommend this though. Native date/time functions are way better coping with invalid input.

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.

Check PHP datetime stamp is correct?

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.

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.

how to validate date with PHP

If a date is submitted by form in following format, $month=2, $day=31, $year= 2010. How can i verify using PHP date function if it is valid date or not? Thanks.
http://php.net/manual/en/function.checkdate.php
The checkdate function is the first result in google from the search "php validate date"
In your case, the usage would be:
checkdate($month, $day, $year);
<?php
function validateDate($date, $format = 'Y-m-d H:i:s'){
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) == $date;
}
?>
var_dump(validateDate('2012-02-28 12:12:12')); # true
var_dump(validateDate('2012-02-30 12:12:12')); # false
var_dump(validateDate('2012-02-28', 'Y-m-d')); # true
var_dump(validateDate('28/02/2012', 'd/m/Y')); # true
var_dump(validateDate('30/02/2012', 'd/m/Y')); # false
function was copied from this answer or php.net
Try checkdate()
http://php.net/manual/en/function.checkdate.php
checkdate($month, $day, $year);
returns true if date is valid / false otherwise
bool checkdate ( int $month , int $day , int $year )
Here's what I've come up with to combine the strictness of checkdate() with the convenience of DateTime (It converts entries like 'next thursday' or '2 weeks ago')
If the input string is invalid, it returns false. Empty dates are returned as null, and non-empty dates are formatted MySQL style 'Y-m-d'.
/**
* #return variant null for empty date, mysql date string for valid date, or false for invalid date string
*/
function myCheckDate($date)
{
$result=false;
if($date=='')
{
$result=null;
}
else
{
//Best of both worlds
// - flexibility of DateTime (next thursday, 2 weeks ago, etc)
// - strictness of checkdate (2000-02-31 is not allowed)
$m=false;
$d=false;
$y=false;
$parts=date_parse($date);
if($parts!==false)
{
$m=$parts['month'];
$d=$parts['day'];
$y=$parts['year'];
}
if($m!==false && $d!==false)
{
if($y===false) $y=date('Y'); //Default to this year
//Try for a specific date - this catches bad entries like 'feb 31, 2000'
if(checkdate($m,$d,$y)) $result=sprintf('%04d-%02d-%02d',$y,$m,$d);
}
else
{
//Try for something more generic - this allows entries like 'next thursday'
$dt=false;
try{ $dt=new \DateTime($date); }catch(\Exception $e){ $dt=false; }
if($dt!==false) $result=$dt->format('Y-m-d');
}
}
return $result;
}

Categories