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;
}
Related
Hello all I have two functions. One to check if current day is weekday and if so return a string of the current day. The other to check if current day is weekend and if so return a string of the current day.
For whatever reason the getWeekend() function always return false even if current date is saturday. Please see code below. Maybe I am doing something wrong....
public function getWeekday()
{
date_default_timezone_set('America/New_York');
$today = \date("l");
if ($today == "Monday") {
return "Monday";
} elseif ($today == "Tuesday") {
return 'Tuesday';
} elseif ($today == "Wednesday") {
return 'Wednesday';
} elseif ($today == "Thursday") {
return "Thursday";
} elseif ($today == "Friday") {
return 'Friday';
} else {
throw new \Exception('Not a valid date.');
}
}
public function getWeekend()
{
date_default_timezone_set('America/New_York');
$today = \date("l");
if ($today == "Saturday") {
return "Saturday";
} elseif ($today == 'Sunday') {
return 'Sunday';
} else {
throw new \Exception('Not a valid date.');
}
}
It will surely throw an exception because the date() is returning the value as Friday for today.
You can check the function for Saturday by by setting the $today = 'Saturday'; Or you can try tomorrow it will work perfectly as desired.
I've created this function when retrieving a date from database and echo in Italian format to screen:
function get_data_ita($date) {
if ($date == "")
return "";
$d = new DateTime($date);
return $d->format('d/m/Y');
}
where $date is mysql format like: 2017-12-31 14:00:00
Now, if I pass a correct format like: 2017-12-31 14:00:00 the function works.
But sometimes I need to use the SAME function, passing an already formatted date like: 30/12/2017. In this case, i get parsing error of course.
How can I check if date passed is already in Italian format, and if yes return the untouched date, if not, parse the date?
I need a function like:
function get_data_ita($date) {
if ( $date== ALREADY_IN_ITALIAN_FORMAT )
return $date;
if ($date == "")
return "";
$d = new DateTime($date);
return $d->format('d/m/Y');
}
echo get_data_ita("30/12/2017");
echo get_data_ita("2017-12-31 14:00:00");
ECHO:
30/12/2017
31/12/2017
UPDATE: I found solution myself:
function validateDate($date, $format = 'Y-m-d')
{
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) == $date;
}
function get_data_ita($datetime_db) {
if ( validateDate($datetime_db, 'd/m/Y') ) {
return $datetime_db;
}
if ($datetime_db == "")
return "";
$date = new DateTime($datetime_db);
return $date->format('d/m/Y');
}
Replace / to -
<?php
function get_data_ita($date) {
if ($date == ""){
return "";
}
$date = str_replace('/','-',$date);
$d = new DateTime($date);
return $d->format('d/m/Y');
}
echo get_data_ita("30/12/2017");
echo "\n";
echo get_data_ita("2017-12-31 14:00:00");
?>
Check demo : https://eval.in/918149
Strtotime returns false if the date is not a valid date format.
This works for your inputs but not if there are other date formats.
function get_data_ita($date) {
if ($date == "") return "";
If(strtotime($date) !== False){
$d = new DateTime($date);
}Else{
$d = DateTime::createFromFormat('d/m/Y', $date);
}
return $d->format('d/m/Y');
}
echo get_data_ita("30/12/2017");
echo get_data_ita("2017-12-31 14:00:00");
https://3v4l.org/kt5Vg
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)
);
Ok sorry about the wording on this one but it's doing my head in, I need to find the earliest delivery date,
$useStartDate = mktime(0, 0, 0, date("m") , date("d")+1, date("Y"));
I have 2 functions
The first checks to see if a date is a weekend or a Monday and increments it accordingly
function checkWeekend ($CheckDateDate){
if (date("w", $CheckDateDate) == 1) { //monday
return strtotime('+1 day', $CheckDateDate);
}
else if (date("w", $CheckDateDate) == 0) { //sunday
return strtotime('+2 day', $CheckDateDate);
}
else if (date("w", $CheckDateDate) == 6) { //saturday
return strtotime('+3 day', $CheckDateDate);
}
else {
return 0;
}
}
The second check to see if the date is in my database of holidays
function checkHoliday ($CheckDateDate) {
$result = mysql_query("SELECT * FROM tblNonDeliveryDates Where NonDeliveryDate = '$CheckDateDate'");
if (mysql_num_rows($result) > 0) {
return strtotime('+1 day', $CheckDateDate);
}
else {
return 0;
}
}
Now what I want to do is check both functions until they both return 0, Where I'm having trouble going back and checking the date is not a weekend after it's been incremented because it's a Holidays. This is what I have, but I know that it's wrong.
$CheckDate = $useStartDate;
while ($Checkdate > 0)
{
$LastChecked = $CheckDate;
$Checkdate = checkWeekend($CheckDate);
$Checkdate = checkHoliday($CheckDate);
}
echo $LastChecked;
Hope that's clear.
You can try like this
$CheckDate = $useStartDate;
while ($Checkdate > 0)
{
$weekend = false;
$holiday = false;
if( checkWeekend($Checkdate) != 0)
$weekend = true;
else if( checkHoliday($Checkdate) != 0)
$holiday = true;
else
$Checkdate = 0;
if( $weekend )
$Checkdate = checkWeekend($Checkdate);
else if( $holiday )
$Checkdate = checkHoliday($Checkdate);
$LastChecked = $Checkdate;
}
echo $LastChecked;
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to check if a date is in a given range?
How to check if date(entered by user) is in given range (Date format :-day month ie.:-1 june )
I am trying to find whether a date is in defined range. I'm using the following code:
$apple='25 March';
$udate= date('d F',strtotime($apple));
echo $udate;
$startDate='21 March';
$realStartDate= date('d F',strtotime($startDate)) ;
echo $realStartDate;
$endDate='19 April';
$realEndDate= date('d F',strtotime($endDate)) ;
if ($udate >= $realStartDate && $udate <= $realEndDate ) {
echo 'within tange';
}
else{
echo 'Not in range';
}
?>
Where am I going wrong?
try this one its working......
<?php
$udate = '25 March';
$udateTimestamp = strtotime($udate);
$startDate = '21 March';
$startDateTimestamp = strtotime($startDate);
$endDate = '19 April';
$eEndDateTimestamp = strtotime($endDate);
if ($udateTimestamp >= $startDateTimestamp && $udateTimestamp <= $eEndDateTimestamp)
{
echo 'within tange';
}
else
{
echo 'Not in range';
}
?>
Compare timestamps not the string representations!
if(strtotime($apple) < strtotime($endDate) && strtotime($apple) > strtotime($startDate)){
// All ok!
}
Like this
if(strtotime($givendate) > strtotime('3/21/xxxx') && strtotime($givendata) < strtotime('4/19/xxxx')) {
// Its within range
}
You can use DateTime
$userDate = new DateTime("2012-03-01");
if ( $userDate > new DateTime("2012-03-21 00:00:00") && $userDate < new DateTime("2012-04-19 23:59:59"))
{
// In Range
}
Putting it in a function if format is (1 july)
if (inRange ( "1 June", "3 March", "7 December" )) {
echo "In Range";
} else {
echo "Out Of Range";
}
function inRange($dateCheck, $dateFrom, $dateTo) {
$date = DateTime::createFromFormat ( "d F", $dateCheck );
$date1 = DateTime::createFromFormat ( "d F", $dateFrom );
$date2 = DateTime::createFromFormat ( "d F", $dateTo );
if ($date > $date1 && $date < $date2) {
return true;
}
return false;
}
try this
if (strtotime($udate) >= strtotime($realStartDate) && strtotime($udate) <= strtotime($realEndDate) ) {
echo 'within tange';
}
else{
echo 'Not in range';
}