When a user attempts to register with my site, I need to verify that they are old enough. I am trying to do this using the getdate() function.
I understand what getdate() does, but I am struggling to understand how to use it correctly for this purpose.
<?php
$fn = $_POST["fullname"];
$un = $_POST["username"];
$pw = $_POST["password"];
$dob = $_POST["dayofbirth"];
$mob = $_POST["monthofbirth"];
$yob = $_POST["yearofbirth"];
$date = getdate();
if ( $yob =$yob>= $date["year"]-16)
{
echo "Too young to register!";
}
elseif ($yob <=1899)
{
echo "Don't be silly, you are not that old!";
}
else
{
echo "<h1>Thank you for registering with us!</h1>";
echo "<p> You have successfully registered with these details:
<br>Your full name :$fn<br> Username: $un
<br>Date of birth: $dob $mob $yob</p>";
}
?>
Try:
$registration = new DateTime(implode('-', array($yob, $mob, $dob)));
$now = new DateTime();
var_dump($now->diff($registration)->y);
This will give you the actual age, taking months, days and leap years into account.
DateTime Class Manual
If you correct this if ( $yob =$yob>= $date["year"]-16) to if ( $yob >= $date["year"]-16), then this will do what you're expecting it to and it will work some of the time. The problem is that depending on when someone's birthday is in the year compared to the current date, just subtracting the year like this will often give an incorrect result.
A better way would be to calculate the age using the DateTime::diff method. This should get you the person's exact age.
$age = date_create("$yob-$mob-$dob")->diff(new DateTime());
Then you can compare the year property of the resulting DateInterval object to verify the age.
if ( $age->y < 16) {
echo "Too young to register!";
} elseif ($age->y > 117) {
echo "Don't be silly, you are not that old!";
} else { ...
Related
For some reason I am having difficulties comparing a previous date and current date. I have tried many different things, and tried to google my way to an answer but with no luck.
This is how my code is..
$phpdate = date("Y-m-d");
$sql = "SELECT lastDailyCollect FROM users WHERE steamid='".$_POST['steamid']."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$lastDailyCollect = $row['lastDailyCollect'];
}
}
if ($lastDailyCollect == $phpdate) {
//give user error message
}elseif ($lastDailyCollect != $phpdate) {
//let user know it suceeded
}else {
//comparison error
}
I want to check if the user is able to collect a daily bonus. The last collection date of each user is stored in a mysql database, in a table called users.
It always goes to the comparison error.
Hope somebody can help.
What you can do to check if lastDailyCollect date was previous day by subtracting one day from the current date and storing it in $yesterday then matching if previous date is equal to lastDailyCollect date.
<?php
$date = date("Y-m-d"); //2017-05-12
$lastDailyCollect = "2017-05-11";
$yesterday = date('Y-m-d',strtotime($date . "-1 days")); //2017-05-11
if($lastDailyCollect == $yesterday) {
//give user error message
echo 'lastDailyCollect is equal to Previous day';
}
else
{
//let user know it suceeded
echo 'lastDailyCollect is not equal to previous day';
}
?>
I had visited some of the post retrieving the date difference between 2 dates in SO but it doesn't gave me the answer I was seeking. Same for reading the documentation, I had problem understanding how it works.
I have tried coding it but it doesn't behave like what I was expecting. Here is my code:
<?php
$currentDate = new DateTime();
$createDateJoin = date_create($getDate['date_joined']);
$dateJoin = date_format($createDateJoin, "Y-m-d");
$yearDifference = $currentDate->diff($createDateJoin);
if ($yearDifference->d < 31 && $yearDifference->m = 0 && $yearDifference->y == 0) {
echo $yearDifference->d . " days";
} else if ($yearDifference->m > 3) {
echo $yearDifference->m . " month";
} else if ($yearDifference->y > 1) {
echo $yearDifference->y . " years";
} else {
echo "Not yet assigned";
}
?>
As you can see from my code above, I am trying to do a print when after calculating the difference between the 2 dates, it meets the condition of $yearDifference->.The behavior from the program that I have experienced does not print out the things I want accordingly (E.g Staff working more than 1 year will print out how many years they have work, months for those who just came in and new staff less than a month will print out days).
I would like to know how does ->d/m/y works and how can I actually make use of the d,m and y to draw out the specific date correctly. And I also noticed that when I treat $yearDifference as a String or int, it comes out different result for the conditions. So what should I treat the type to be to manipulate it more easily? Greatly appreciate the help.
You can use this code to get the date different method diff() object returns more values to check you can print_r your object that will print all data member that are returned via diff() method
<?php
echo get_date_diff(strtotime('1990-10-12'),strtotime('2015-10-14'));
function get_date_diff($date,$dateEnd) {
$dStart = new DateTime(date("Y-m-d", $date));
$dEnd = new DateTime(date("Y-m-d", $dateEnd));
$dDiff = $dStart->diff($dEnd);
return($dDiff->y.' years <br>'.$dDiff->m.' months <br>'.$dDiff->d. ' days');
}
?>
I've looked at many posts on here and I still cant figure this out.
I am trying to verify that someone is older than 13 before they register for my site. This is what i have so far
<?php
if (is_string($_POST['birthday']) && $_POST['birthday'] != 'mm/dd/yyyy')
{
$dateObj = new DateTime($_POST['birthday']);
$ageLimit = new DateTime('13 years');
$now = new DateTime(date("Y/m/d"));
$checkDate = $now->diff($ageLimit);;
if($checkDate > $dateObj)
{
$errors[]='You must be atleast 13 years old to join.';
}
else
{
$bday = mysqli_real_escape_string($db,$_POST['birthday']);
}
}
else
{
$errors[]= 'Enter your birthday.';
}
The code will always run to
$bday = mysqli_real_escape_string($db,$_POST['birthday']);}
no matter what is entered in the date field and the outcome is always 1.
Can anyone help me with this? I cant figure this one out on my own.
<b>Birth Date</b><br><input type="date" name="birthday"
value=<?php if(isset($_POST['birthday']))echo $_POST['birthday'];?>><br>
Comparaison operators work with DateTime, see the answer here.
So something like this should work
$dateObj=new DateTime($_POST['birthday']);
$ageLimit=new DateTime('-13 years');
if($dateObj > $ageLimit){
//TOO YOUNG
}
EDIT per comment
Replace
if(isset($_POST['birthday']))echo $_POST['birthday'];
with
if(isset($_POST['birthday'])) {
echo $_POST['birthday'];
} else {
echo 'mm/dd/yyyy';
}
Or change
if (is_string($_POST['birthday']) && $_POST['birthday'] != 'mm/dd/yyyy')
To
if (!empty($_POST['birthday']) && is_string($_POST['birthday']))
You have several errors
'13 years' is not a valid value for DateTime()
A date in the 'Y/m/d' format is not a valid format for DateTime()
$checkDate is a DateInterval object and is not comparable to a DateTime object
You can fix this and simplify your code by comparing DateTime objects which are comparable:
$birthday = new DateTime($_POST['birthday']);
$ageLimit = new DateTime('-13 years');
if ($birthday < $ageLimit) {
// they're old enough
}
else {
// too young
}
Demo
It might be easier to use strtotime to calculate the date difference. The higher the number the younger somebody is. So if the persons age is higher than the minimal age number they are not old enough.
if(is_string($_POST['birthday'])&&$_POST['birthday']!='mm/dd/yyyy') {
$minAge = strtotime("-13 years");
$dateObject = strtotime($_POST['birthday']);
if($dateObject > $minAge) {
$errors[]= 'You must be atleast 13 years old to join.';
}
} else {
$errors[]='Enter your birthday.';
}
In my database I have one table in which I keep registered users.
One column is Date of register and I keep this value in my own string format.
For example "[2013-11-30] [19:42:46]"
Then I want to make a check.
If user is 30 days old or more.
The sure thing is that the above code is wrong.
The problem is that if one user registers at 29/01/2015
will not been showing in 30 last days if the current day is 02/02/2015!
//Datetime
$today = date_parse_from_format("[Y-m-d] [H:i:s]", gmdate("[Y-m-d] [H:i:s]"));
$store = date_parse_from_format("[Y-m-d] [H:i:s]", $row["LastSeen"]);
if (
(($store[year] >= $today[year]) && ($store[month] >= $today[month]))
)
{ $date_last = "<font color='green'>".$row["LastSeen"]."</font>"; }
else
{ $date_last = "<font color='red'>".$row["LastSeen"]."</font>"; }
Use date_create_from_format instead of date_parse_from_format. Then you can simply compare the resulting values:
$today = date_create_from_format("[Y-m-d] [H:i:s]", gmdate("[Y-m-d] [H:i:s]"));
$store = date_create_from_format("[Y-m-d] [H:i:s]", $row["LastSeen"]);
if ($store < $today) {
// ...
}
else {
// ...
}
I have tried every combo I can think of / found and no matter what I do, my codet echos the message even if the account isn't locked out:
<?php
$infosql = "SELECT * FROM premiersounds_users WHERE customer_id = $id";
$inforesult = mysql_query($infosql) or die(mysql_error());
$info = mysql_fetch_array($inforesult);
//Get current date from server
$format="%m/%d/%y";
$c_date=strftime($format);
//set sessions
$_SESSION['current_date'] = $c_date;
//The date in the database is 10/31/11
$_SESSION['lockout_date'] = $l_date;
//Check is Current date = lockout date
if ($c_date <= $l_date) {
header("location:documnet_editors/edit_weddingplanner.php?id=$id");
}
else {
echo 'Whoops! Were sorry your account has been locked to edits
because your event is less than 48 hours from now or your event has passed.
To make changes to your event please contact your DJ.';
}
?>
<?php
//Destroy Session for Lockout Date to prevent bypasses
unset($_SESSION['lockout_date']);
?>
If your $l_date is populated, and I don't think it is, if it is stored as MM/DD/YY, you'll want to use PHP's strtotime to convert it to a unix timestamp for quick comparison:
if( strtotime($db_date) >= time() )
{
// do something
}
I would suggest comparing timestamps instead of formatted dates:
<?php
$date_a = new DateTime();
$date_b = new DateTime('2000-10-20 00:10:20');
if ($date_a->getTimestamp() > $date_b->getTimestamp()) {
echo 1;
} else {
echo 0;
}
convert your dates to unixtime for more accurate comparison. Add this function to your code:
function unix_time($date){
$unix_date = str_replace("-","/",$date);
$unix_date = str_replace(".","/",$unix_date);
$unix_date = str_replace(" pm","",$unix_date);
$unix_date = str_replace(" am","",$unix_date);
$time = strtotime($unix_date);
return $time;
}
then convert the dates to unix:
$l_date = unix_time($_SESSION['lockout_date']);
$c_date = unix_time($_SESSION['current_date']);
or you can also get the date directly from the database:
$l_date = unix_time($info['date_in_database']);
compare the dates in unix format:
if ($c_date = $l_date) {
// your code here
}
this should work.