Date/time validation in PHP - php

I'm trying to take individual values for date/time from a form submission and parse them into a date of a certain format.
If validation fails for any reason (e.g. 30th Feb, 13th month, etc) then the result should default to the current time.
if (isset($_POST['year'], $_POST['month'], $_POST['day'], $_POST['hour'], $_POST['minute']))
{
$y = $_POST['year'];
$m = $_POST['month'];
$d = $_POST['day'];
$h = $_POST['hour'];
$i = $_POST['minute'];
if (checkdate($m, $d, $y))
{
if ($h >= 0 && $h <= 23)
{
if ($i >= 0 && $i <= 59)
{
$str = $y.'-'.$m.'-'.$d.' '.$h.':'.$i.':00';
$time = strtotime($str);
}
else $time = time();
}
else $time = time();
}
else $time = time();
}
else $time = time();
$datetime = date('D j M Y - H:i:s T', $time);
echo $datetime;
Two things happen which I don't understand:
If one or more date values are missing, an error appears about checkdate()... I can't see why the validation doesn't just fail at the first if()
If one or more time values are missing, the end result is the UNIX Epoch?!

If one or more date values are missing, an error appears about checkdate()... I can't see why the validation doesn't just fail at the first if()
Being set and having a valid value are two different things. A variable can be set and contain an empty string or null. Check to make sure those values actually contain values using empty().
If one or more time values are missing, the end result is the UNIX Epoch?!
If you pass date() an invalid second parameter (i.e. a valid unix timestamp) it defaults to the epoch.

Empty value check before execute checkdata
<?php
if(!empty($y) && !empty($m) && !empty($d) && !empty($h) && !empty($i))
{
if (checkdate($m, $d, $y))
{
if ($h >= 0 && $h <= 23)
{
if ($i >= 0 && $i <= 59)
{
$str = $y.'-'.$m.'-'.$d.' '.$h.':'.$i.':00';
$time = strtotime($str);
}
else $time = time();
}
else $time = time();
}
else $time = time();
}
else $time = time();
$datetime = date('D j M Y - H:i:s T', $time);
echo $datetime;
?>

Related

PHP Dates Condition [duplicate]

How can I compare two dates in PHP?
The date is stored in the database in the following format
2011-10-2
If I wanted to compare today's date against the date in the database to see which one is greater, how would I do it?
I tried this,
$today = date("Y-m-d");
$expire = $row->expireDate //from db
if($today < $expireDate) { //do something; }
but it doesn't really work that way. What's another way of doing it?
If all your dates are posterior to the 1st of January of 1970, you could use something like:
$today = date("Y-m-d");
$expire = $row->expireDate; //from database
$today_time = strtotime($today);
$expire_time = strtotime($expire);
if ($expire_time < $today_time) { /* do Something */ }
If you are using PHP 5 >= 5.2.0, you could use the DateTime class:
$today_dt = new DateTime($today);
$expire_dt = new DateTime($expire);
if ($expire_dt < $today_dt) { /* Do something */ }
Or something along these lines.
in the database the date looks like this 2011-10-2
Store it in YYYY-MM-DD and then string comparison will work because '1' > '0', etc.
Just to compliment the already given answers, see the following example:
$today = new DateTime('');
$expireDate = new DateTime($row->expireDate); //from database
if($today->format("Y-m-d") < $expireDate->format("Y-m-d")) {
//do something;
}
Update:
Or simple use old-school date() function:
if(date('Y-m-d') < date('Y-m-d', strtotime($expire_date))){
//echo not yet expired!
}
I would'nt do this with PHP.
A database should know, what day is today.( use MySQL->NOW() for example ), so it will be very easy to compare within the Query and return the result, without any problems depending on the used Date-Types
SELECT IF(expireDate < NOW(),TRUE,FALSE) as isExpired FROM tableName
$today = date('Y-m-d');//Y-m-d H:i:s
$expireDate = new DateTime($row->expireDate);// From db
$date1=date_create($today);
$date2=date_create($expireDate->format('Y-m-d'));
$diff=date_diff($date1,$date2);
//echo $timeDiff;
if($diff->days >= 30){
echo "Expired.";
}else{
echo "Not expired.";
}
Here's a way on how to get the difference between two dates in minutes.
// set dates
$date_compare1= date("d-m-Y h:i:s a", strtotime($date1));
// date now
$date_compare2= date("d-m-Y h:i:s a", strtotime($date2));
// calculate the difference
$difference = strtotime($date_compare1) - strtotime($date_compare2);
$difference_in_minutes = $difference / 60;
echo $difference_in_minutes;
You can convert the dates into UNIX timestamps and compare the difference between them in seconds.
$today_date=date("Y-m-d");
$entered_date=$_POST['date'];
$dateTimestamp1 = strtotime($today_date);
$dateTimestamp2 = strtotime($entered_date);
$diff= $dateTimestamp1-$dateTimestamp2;
//echo $diff;
if ($diff<=0)
{
echo "Enter a valid date";
}
I had that problem too and I solve it by:
$today = date("Ymd");
$expire = str_replace('-', '', $row->expireDate); //from db
if(($today - $expire) > $NUMBER_OF_DAYS)
{
//do something;
}
Here's my spin on how to get the difference in days between two dates with PHP.
Note the use of '!' in the format to discard the time part of the dates, thanks to info from DateTime createFromFormat without time.
$today = DateTime::createFromFormat('!Y-m-d', date('Y-m-d'));
$wanted = DateTime::createFromFormat('!d-m-Y', $row["WANTED_DELIVERY_DATE"]);
$diff = $today->diff($wanted);
$days = $diff->days;
if (($diff->invert) != 0) $days = -1 * $days;
$overdue = (($days < 0) ? true : false);
print "<!-- (".(($days > 0) ? '+' : '').($days).") -->\n";
Found the answer on a blog and it's as simple as:
strtotime(date("Y"."-01-01")) -strtotime($newdate))/86400
And you'll get the days between the 2 dates.
This works because of PHP's string comparison logic. Simply you can check...
if ($startdate < $date) {// do something}
if ($startdate > $date) {// do something}
Both dates must be in the same format. Digits need to be zero-padded to the left and ordered from most significant to least significant. Y-m-d and Y-m-d H:i:s satisfy these conditions.
If you want a date ($date) to get expired in some interval for example a token expiration date when performing a password reset, here's how you can do:
$date = $row->expireDate;
$date->add(new DateInterval('PT24H')); // adds 24 hours
$now = new \DateTime();
if($now < $date) { /* expired after 24 hours */ }
But in your case you could do the comparison just as the following:
$today = new DateTime('Y-m-d');
$date = $row->expireDate;
if($today < $date) { /* do something */ }
first of all, try to give the format you want to the current date time of your server:
Obtain current date time
$current_date = getdate();
Separate date and time to manage them as you wish:
$current_date_only = $current_date[year].'-'.$current_date[mon].'-'.$current_date[mday];
$current_time_only = $current_date['hours'].':'.$current_date['minutes'].':'.$current_date['seconds'];
Compare it depending if you are using donly date or datetime in your DB:
$today = $current_date_only.' '.$current_time_only;
or
$today = $current_date_only;
if($today < $expireDate)
hope it helps

How to check the time range in array are exist in between two time variable in PHP

I have this time range in array example:
$timerange = array('01:30:00','01:31:00',...........,'02:30:00');
and 2 variable:
$start_time = '01:15:00';
$end_time = '03:29:00';
if($timerange is between $start_time && $end_time)
{
//do it something if yes.....
}
Please help me, its have any ready function to use in PHP? to check on this.
You need not bother with conversions of your time strings to a time type - you can compare the strings as they are:
<?php
$timerange = array('01:30:00', '01:31:00', '01:32:00', '02:30:00');
$start_time = '01:15:00';
$end_time = '03:29:00';
$between = array();
foreach ($timerange as $time)
if ($start_time <= $time && $time <= $end_time) $between[] = $time;
if ($between)
{
echo "These are the times between $start_time and $end_time:\n";
print_r($between);
}
If you like it better, you can replace the foreach loop with array_filter():
$between = array_filter($timerange,
function($time) use ($start_time, $end_time)
{ return $start_time <= $time && $time <= $end_time; }
);
<?php
$timerange = array(strtotime('01:30:00'), strtotime('01:31:00'), strtotime('03:30:00'));
$start_time = strtotime('01:15:00');
$end_time = strtotime('03:29:00');
foreach($timerange as $key => $text_field){
if($timerange[$key] > $start_time && $timerange[$key] < $end_time){
echo "Existing";
}else{
echo "Not Existing";
}
}
?>
See How to check if a date is in a given range?
Edit: As you are looking in a 24 hour range you can pick and random date when constructing your timestamps and your calculations should hold true as all of them are the same date.
return (($user_ts >= $start_ts) && ($user_ts <= $end_ts));
Where all of those are timestamps.
Also look at this PHP check if time falls within range, questioning common solution if you don't want this to depend on the date but just the time.

Getting some issue when executing query of time

I'm fetching time from data database and executing some condition but it's not work properly. I can't understand what's is problem in this code. My code
date_default_timezone_set('Asia/Kolkata');
$currentDay=date("l");
$status="SELECT * FROM nesbaty_working_time WHERE provider_id='".$r."' AND day='".$currentDay."'";
$qry_res2 = mysqli_query($con, $status);
$array1 = mysqli_fetch_assoc($qry_res2);
$opening_time = $array1['opening_time'];
$closing_time = $array1['closing_time'];
$currentTime=date("h:i A");
if (($opening_time < $currentTime) && ($currentTime < $closing_time))
{
$response['status'] = "Open";
}
else
{
$response['status'] = "Close";
}
what is problem i can't understand. It always execute else part. My database look like this
You can't compare AM/PM times as strings. If the current time is 11:00 AM, it is not less than 05:00 PM, because 1 is greater than 0. And if it's 01:00 PM, it's not greater than 10:00 AM, because 0 is less than 1.
You need to convert the times to 24-hour time to be able to compare them properly. Or just convert them to timestamps.
$currentTime = time();
$openingTime = date_create_from_format('H : i A', $array1['opening_time']);
$closingTime = date_create_from_format('H : i A', $array1['closing_time']);
if ($openingTime <= $currentTime && $currentTime <= $closingTime) {
$response['status'] = "open";
} else {
$response['status'] = "closed";
}
You should try this function to make your data in proper format
$openingTime = date_create_from_format('H : i A', $your_variable);
$closingTime = date_create_from_format('H : i A', $your_variable);

Get time before noon

I am practicing with dates in php. I a bit of a newbie so bear my ignorance
I am trying to see when a time is before noon.
So I have a variable coming in with this format 2014-03-07 13:28:00.000
I get the time like this
$submissonTime = date('H:i:s', strtotime($value['job_submission_date']));
then I want to set another variable as $noon and i am doing this:
$noon = date('H:i:s', '12:00:00.000');
However the value of noon is 12:00:12
what i want to do is basically:
if($submissionTime <= $noon){
//do my stuff
}
NB I want to enter the if statement when even when it is 12:00:00 and stop entering when it is 12:00:01
Any help please?
Try
$noon = date('Y-m-d 12:00:00'); // today noon with date
$submissonTime = date('Y-m-d H:i:s', strtotime($value['job_submission_date']));
if(strtotime($submissonTime) <= strtotime($noon)){
//do my stuff
}
if you want to compare only time use both format
$noon = date('12:00:00');
$submissonTime = date('H:i:s', strtotime($value['job_submission_date']));
if (date("A") == "AM")
{
// AM-Code
} else {
// PM-Code
}
Why don't you go with only one string of code getting the hour?
$Hour = date("G"); //24-hour format of an hour without leading zeros
if($Hour < 12) {
// do the code
}
Or in your case
$Hour = date("G", strtotime($value['job_submission_date']));
update
If you need 12:00:00 and not 12:00:01 and later on, you will need to define minutes and seconds:
$Hour = date("G"); //24-hour format of an hour without leading zeros
$Minute = intval(date("i")); // will give minutes without leading zeroes
$Second = intval(date("s"));
if(($Hour < 12) || ($Hour == 12 && $Minute == 0 && Second == 0)) {
// do the code
}

Adding months to a date and insert into database

i'm trying to add X month to a date taken from my database
$sql_batch = "SELECT * FROM mgm_subscription WHERE status = '1'"
$query_batch = mysql_query($sql_batch);
$row_batch = mysql_fetch_array($query_batch);
$addMonth = 3;
$startDate = $row_batch['start_month'];
$endDate = strtotime('+'.$addMonth.' month', $startMonth); // add number of days from form
$endDate = date('m/d/y H:i:s', $endDate );
$sql_date = "INSERT INTO user_subscription (user_id, start_month, end_month, sub_status) VALUES ('".$usercode2."','".$startDate."','".$endDate."', '')";
$query_date = mysql_query($sql_date);
NULL was inserted into the end_month.
start_month and end_month is DATE type in the mysql
how do i fix this? tq.
If I understood your question, your $endDate should be
$endDate = date('Y-m-d', strtotime($startDate.' +'.$addMonth.' months'));
So this will equate to:
$endDate = $startDate + 3 months /* in Y-m-d format */
EDIT: Just saw that your column datatype is Date. This would mean that you can't store timestamp in your date. It has to be Y-m-d format only as that is the valid mysql format supported.
You insert $endMonth a value(number of days from form) then you try to replace it ($endMonth) and you call back your replaced variable..
$endMonth = strtotime('+'.$addMonth.' month', $startMonth); // add number of days from form
$endMonth = date('m/d/y H:i:s', $endMonth);
It will return null value.. My suggestion, try to put other variable to prevent duplicate value or missing data
You only mention adding X months. Maybe I misunderstood your question, but if all you care about is the month, I would do the following:
if ($startMonth === 'January') {
$monthNumber = 1;
} else if ($startMonth === 'February') {
$monthNumber = 2;
} //Up to November then finish with {
else {
$monthNumber = 12;//December
}
$newMonthNumber = $monthNumber + $addMonth;
if ($newMonthNumber % 12 == 1) {
$endMonth = 'January';
} else if ($newMonthNumber % 12 == 1) {
$endMonth = 'February';
} //Up to November then finish with {
else {
$endMonth = 'December';
}
$sql_date = "INSERT INTO user_subscription (user_id, start_month, end_month, sub_status) VALUES ('".$usercode2."','".$startMonth."','".$endMonth."', '')";
$query_date = mysql_query($sql_date);

Categories