how can i calculate date not less than 18 - php

I am trying to find the date not less than 18 years, I tried this following code, but its not working for me.
// validate birthday
function validateAge($then, $min)
{
// $then will first be a string-date
$then = strtotime($then);
echo "<br>";
echo 'test1-';
var_dump( $then );
exit;
//The age to be over, over +18
$min = strtotime('+18 years', $then);
if(time() < $min) {
die('Not 18');
}
}
$res = validateAge('2016-02-29', $min = 18);
var_dump($res);
I fyou see the above question, you can see that, date is not valid, even if i pass the wrong date, its shows the $then = strtotime($then);
var_dump($then) show the int
my question is, how its printing the timestamp, event if we passing the invalid date.

Your logic is correct. Remove die, exit and echo which is not needed
function validateAge($then, $min)
{
// $then will first be a string-date
$then = strtotime($then);
//The age to be more then min years
$min = strtotime('+'. $min . ' years', $then);
return time() > $min;
}
$res = validateAge('2016-02-29', $min = 18);
echo $res ? 'O\'key' : "Not $min years";
demo

Try maybe something like this
function compareAge($date,$min=18)
{
$strdate = strtotime($date);
$curdate = strtotime("today");
$datefin=date("Ymd",$curdate)-date("Ymd",$strdate);
$age=substr($datefin,0,strlen($datefin)-4);
return $age>=$min;
}
var_dump(compareAge("2013-05-13"));
DEMO

you could use this method:
public function validateAge($then)
{
$then= date_create($then);
$now = date_create("now");
$diff = $now->diff($then);
if ($diff->y > 18)
{
die('not 18');
}
}
Duplicate:
Calculating number of years between 2 dates in PHP

use the datetime object to save all sorts of pain. Its so much more simple.
function validateAge(DateTime $then, $min = 18)
{
$now = new DateTime();
$minimum = clone($now); // you could just modify now, but this is simpler to explain
$minimum->modify("-$min years");
if($then < $minimum) {
return false;
}
return true;
}
echo validateAge(new DateTime('1-1-1997')) ? 'true' : 'false'; // returns false
echo validateAge(new DateTime('1-1-1999')) ? 'true' : 'false'; // returns true
see example

Wow, so many try-hards.
In case you like is simple:
<?php
function validateAge($date) {
return date_create('18 years ago') > date_create($date);
}
var_dump(
validateAge('2010-10-05'),
validateAge('1992-09-02')
);
OUTPUT
bool(false)
bool(true)
Play with me on 3v4l.org
Edit: Also works with the $min parameter:
<?php
function validateAge($date, $min) {
return date_create("$min years ago") > date_create($date);
}
var_dump(
validateAge('2010-10-05', 18),
validateAge('1992-09-02', 18)
);

Related

php carbon check if now is between two times (10pm-8am)

$start = '22:00:00';
$end = '08:00:00';
$now = Carbon::now('UTC');
How can I check if the time of $now is within the timerange?
There are several ways to achieve that by using Carbon. One of the easiest ways is using createFromTimeString and between methods:
$now = Carbon::now();
$start = Carbon::createFromTimeString('22:00');
$end = Carbon::createFromTimeString('08:00')->addDay();
if ($now->between($start, $end)) {
// ¯\_(ツ)_/¯
}
Try this:
$time = Carbon::now();
$morning = Carbon::create($time->year, $time->month, $time->day, 8, 0, 0); //set time to 08:00
$evening = Carbon::create($time->year, $time->month, $time->day, 18, 0, 0); //set time to 18:00
if($time->between($morning, $evening, true)) {
//current time is between morning and evening
} else {
//current time is earlier than morning or later than evening
}
The true in $time->between($morning, $evening, true) checks whether the $time is between and including $morning and $evening. If you write false instead it checks just if it is between the two times but not including.
Actually, you could leave true away because it is set by default and not needed.
Check here for more information on how to compare dates and times with Carbon.
$start = '22:00:00';
$end = '08:00:00';
$now = Carbon::now('UTC');
$time = $now->format('H:i:s');
if ($time >= $start && $time <= $end) {
...
}
Should do it, but doesn't take date into consideration
You can reverse check algorithm.
<?php
$pushChannel = "general";
$now = Carbon::now();
$start = Carbon::createFromTime(8, 0);
$end = Carbon::createFromTime(22, 0);
if (!$now->between($start, $end)) {
$pushChannel = "silent";
$restrictStartTime = Carbon::createFromTime(22, 0, 0); //carbon inbuild function which will create todays date with the given time
$restrictEndTime = Carbon::createFromTime(8, 0, 0)->addDays(1); //this will create tomorrows date with the given time
$now = Carbon::now();
if($now->gt($restrictStartTime) && $now->lt($restrictEndTime)) {
.....
}
Please Try below code,
$start = '22:00:00';
$end = '08:00:00';
$now = Carbon::now('UTC');
$nowTime = $now->hour.':'.$now->minute.':'.$now->second;
if(strtotime($nowTime) > strtotime($start) && strtotime($nowTime) < strtotime($end) ) {
echo 'YES';
} else {
echo 'NO';
}
What Chris is trying to point out is if the endtime crosses over midnight then you must account for that.
This is not the cleanest way to do it but here is a method that seems to work.
private function isNowBetweenTimes($timezone, $startDateTime, $endDateTime) {
$curTimeLocal = Carbon::now($timezone);
$startTime = $curTimeLocal->copy();
$startTime->hour = $startDateTime->hour;
$startTime->minute = $startDateTime->minute;
$endTime = $curTimeLocal->copy();
$endTime->hour = $endDateTime->hour;
$endTime->minute = $endDateTime->minute;
if ($endTime->lessThan($startTime))
$endTime->addDay();
return ($curTimeLocal->isBetween($startTime, $endTime));
}
This example only cares about the hour and minutes and not the seconds but you can easily copy that as well. The key to this is comparing start and end time before comparing them to the current time and add a day to end time if end time is less than start time.
For complete solution which supports all start and end time range you can use bitwise XOR.
/*
* must using hours in 24 hours format e.g. set 0 for 12 pm, 6 for 6 am and 13 for 1 pm
*/
private $startTime = '0';
private $endTime = '6';
$currentHour = \Carbon\Carbon::now()->hour;
$start = $this->startTime > $this->endTime ? !($this->startTime <= $currentHour) : $this->startTime <= $currentHour;
$end = $currentHour < $this->endTime;
if (!($start ^ $end)) {
//Do stuff here if you want exactly between start and end time
}
an updated version of #AliN11's answer taking into account ranges accross two days or in the same day
$now = now();
$start = Carbon::createFromTimeString('22:00');
$end = Carbon::createFromTimeString('08:00');
if ($start > $end) {
$end = $end->addDay();
}
if ($now->between($start, $end)||$now->addDay()->between($start, $end)) {
//add statements
}
<?php
$now = date("H");
if ($now < "20") {
echo "Have a good day!";
}
Try this :
$start = 22; //Eg. start hour
$end = 08; //Eg. end hour
$now = Carbon::now('UTC');
if( $start < $now->hour && $now->hour < $end){
// Do something
}
#AliN11's (currently top) answer is good, but doesn't work as one would immediately expect, after midnight it just breaks, as raised in the comments by #Sasha
The solution is to reverse the logic, and check if the time is not between the inverse hours.
Here is an alternative that works as one would expect:
$now = Carbon::now();
$start = Carbon::createFromTimeString('08:00');
$end = Carbon::createFromTimeString('22:00');
if (! $now->between($start, $end)) {
// We're all good
}
Yes, the midnight plays a vital role in time duration. We can find now() being the given time range as follows:
$now = Carbon::now();
$start = Carbon::createFromTime('22', '00');
$end = Carbon::createFromTime('08', '00');
if ($start->gt($end)) {
if ($now->gte($start)) {
$end->addDay();
} elseif ($now->lte($end)) {
$start->subDay();
} else {
return false;
}
}
return $now->between($start, $end);

Check if 2 given dates are a weekend using PHP

I have 2 dates like this YYYY-mm-dd and I would like to check if these 2 dates are a weekend.
I have this code but it only tests 1 date and I don't know how to adapt it; I need to add a $date_end.
$date = '2011-01-01';
$timestamp = strtotime($date);
$weekday= date("l", $timestamp );
$normalized_weekday = strtolower($weekday);
echo $normalized_weekday ;
if (($normalized_weekday == "saturday") || ($normalized_weekday == "sunday")) {
echo "true";
} else {
echo "false";
}
A couple of hints:
date('N') gives you normalised week day you can test against (no need to use localised strings)
Wrap it all in a custom function and you're done
You can use shorter code to check for weekend => date('N', strtotime($date)) >= 6.
So, to check for 2 dates — and not just 1 — use a function to keep your code simple and clean:
$date1 = '2011-01-01' ;
$date2 = '2017-05-26';
if ( check_if_weekend($date1) && check_if_weekend($date2) ) {
echo 'yes. both are weekends' ;
} else if ( check_if_weekend($date1) || check_if_weekend($date2) ) {
echo 'no. only one date is a weekend.' ;
} else {
echo 'no. neither are weekends.' ;
}
function check_if_weekend($date) {
return (date('N', strtotime($date)) >= 6);
}
Using your existing code, which is slightly longer, following is how you would check for 2 dates:
$date1 = '2011-01-01' ;
$date2 = '2017-05-27';
if ( check_if_weekend_long($date1) && check_if_weekend_long($date2) ) {
echo 'yes. both are weekends' ;
} else if ( check_if_weekend_long($date1) || check_if_weekend_long($date2) ) {
echo 'no. only one date is a weekend.' ;
} else {
echo 'no. neither are weekends.' ;
}
function check_if_weekend_long($date_str) {
$timestamp = strtotime($date_str);
$weekday= date("l", $timestamp );
$normalized_weekday = strtolower($weekday);
//echo $normalized_weekday ;
if (($normalized_weekday == "saturday") || ($normalized_weekday == "sunday")) {
return true;
} else {
return false;
}
}
Merging multiple answers into one and giving a bit extra, you'd come to the following:
function isWeekend($date) {
return (new DateTime($date))->format("N") > 5 ? true : false;
}
Or the long way:
function isWeekend($date) {
if ((new DateTime($date))->format("N") > 5) {
return true;
}
return false;
}
You can use the strtotime(); and date() functions to get the day of the date, and then check if is sat o sun
function check_if_weekend($date){
$timestamp = strtotime($date);
$day = date('D', $timestamp);
if(in_array($day, array('sun', 'sat'))
return true;
else return false;
}

Current time plus one for date validation?

I'm having issues with a booking system that i'm trying to customize. It seems that the validation doesn't work on the current date and time if i select the current day.
The validation is a as following.
if (strtotime($str) < time()) {
But that doesn't allow me to book on the current date, even if the time is over current time, not sure if i should add + one to the validation or what. Any ideas would be very helpful.
Here is the full function.
public function _validate_date($str) {
if (strtotime($str) < time()) {
$this->form_validation->set_message('_validate_date', 'Date must be after today, you can only make future reservations!');
return FALSE;
} else {
return TRUE;
}
}
Try the following solution:
$datetime1 = new DateTime($str);
$datetime1->setTime(0, 0, 0);
$datetime2 = new DateTime();
$datetime2->setTime(0, 0, 0);
//get the diff.
$diff = $datetime2->diff($datetime1);
$days = (int) $diff->format("%R%a");
if ($days < 0) {
echo 'past days';
} elseif ($days == 0) {
echo 'today';
} else {
echo 'future days';
}
A working example you can find here: https://3v4l.org/QQ4Pu
Your function with the new solution:
public function _validate_date($str) {
$datetime1 = new DateTime($str);
$datetime1->setTime(0, 0, 0);
$datetime2 = new DateTime();
$datetime2->setTime(0, 0, 0);
//get the diff.
$diff = $datetime2->diff($datetime1);
$days = (int) $diff->format("%R%a");
if ($days <= 0) {
$this->form_validation->set_message('_validate_date', 'Date must be after today, you can only make future reservations!');
return false;
} else {
return true;
}
}
And a working example of your function: https://3v4l.org/HPTVF
If you want check, that current time is not higher current date, try this:
if (strtotime($str) < strtotime(date('Y-m-d 23:59:59')) {

PHP Day count function writing

I need to Write a function named countDays which takes a single parameter named dateinstring which is string in the form ”MM.DD.YYY” represent a real date value. The function should print to the console the number of days from the beginning of the year specified in dateInString until the date represented in dateInString. If the value of dateInString is invalid, the function should print ”Bad format” to the console.
I have written the code as below :
function countDays($dateInString){
date_default_timezone_set('America/Los_Angeles');
$date = explode('.', $dateInString);
if(count($date) == 3 && checkdate($date[0], $date[1], $date[2])){
$formatted_date = $date[2].'-'.$date[0].'-'.$date[1].'00:00:00';
$diff = strtotime($formatted_date).'-'.strtotime($date[2].'-01-01 00:00:00');
echo round($diff/86400)+1;
}
else {
echo 'Bad format';
}
};
countDays('1.15.2014');
But the above code seems that not giving the correct output. It is about 33% correct. But where is the problem with this code ? Please help me!!!
$diff = strtotime($formatted_date).'-'.strtotime($date[2].'-01-01 00:00:00');
Change to
$diff = strtotime($formatted_date) - strtotime($date[2].'-01-01 00:00:00');
You made the minus symbol a string instead of an operator.
You could try it this way
function countDays($dateInString) {
date_default_timezone_set('America/Los_Angeles');
$date = explode('.', $dateInString);
if (checkdate($date[0], $date[1], $date[2])) {
$year_start = mktime(0, 0, 0, 1, 1, $date[2]);
$your_date = mktime(0,0,0,$date[0], $date[1], $date[2]);
$diff = $your_date - $year_start;
echo floor($diff /(60*60*24));
} else {
echo "Bad date supplied";
}
}
A better approach would be to use the DateTime class. I haven't included the validation in this, but i suggest you use regex for that.
function countDays($dateInString){
$parts = explode('.', $dateInString);
$date = new DateTime($parts[2] . '-' . $parts[0] . '-' . $parts[1]);
$compare = new DateTime( $date->format('Y') . '-01-01' );
$interval = $date->diff($compare);
return $interval->format('%a');
}
echo countDays('09.15.2014');
Check this out.
function countDays($dateInString){
date_default_timezone_set('America/Los_Angeles');
$date = explode('.', $dateInString);
if(count($date) == 3 && checkdate($date[0], $date[1], $date[2])){
$formatted_date = strtotime($date[2].'/'.$date[0].'/'.$date[1]);
$endTimeStamp = strtotime("2014/01/01");
$timeDiff = abs($endTimeStamp - $formatted_date);
echo round(intval($timeDiff/86400));
}
else {
echo 'Bad format';
}
};
countDays('01.01.2014');

Calculate years from date

I'm looking for a function that calculates years from a date in format: 0000-00-00.
Found this function, but it wont work.
// Calculate the age from a given birth date
// Example: GetAge("1986-06-18");
function getAge($Birthdate)
{
// Explode the date into meaningful variables
list($BirthYear,$BirthMonth,$BirthDay) = explode("-", $Birthdate);
// Find the differences
$YearDiff = date("Y") - $BirthYear;
$MonthDiff = date("m") - $BirthMonth;
$DayDiff = date("d") - $BirthDay;
// If the birthday has not occured this year
if ($DayDiff < 0 || $MonthDiff < 0)
$YearDiff--;
}
echo getAge('1990-04-04');
outputs nothing :/
i have error reporting on but i dont get any errors
Your code doesn't work because the function is not returning anything to print.
As far as algorithms go, how about this:
function getAge($then) {
$then_ts = strtotime($then);
$then_year = date('Y', $then_ts);
$age = date('Y') - $then_year;
if(strtotime('+' . $age . ' years', $then_ts) > time()) $age--;
return $age;
}
print getAge('1990-04-04'); // 19
print getAge('1990-08-04'); // 18, birthday hasn't happened yet
This is the same algorithm (just in PHP) as the accepted answer in this question.
A shorter way of doing it:
function getAge($then) {
$then = date('Ymd', strtotime($then));
$diff = date('Ymd') - $then;
return substr($diff, 0, -4);
}
An alternative way to do this is with PHP's DateTime class which is new as of PHP 5.2:
$birthdate = new DateTime("1986-06-18");
$today = new DateTime();
$interval = $today->diff($birthdate);
echo $interval->format('%y years');
See it in action
A single line function can work here
function calculateAge($dob) {
return floor((time() - strtotime($dob)) / 31556926);
}
To calculate Age
$age = calculateAge('1990-07-10');
You need to return $yearDiff, I think.

Categories