Check if date is allowed weekday in php? - php

I'm stuck with a problem how to check if a specific date is within allowed weekdays array in php. For example,
function dateIsAllowedWeekday($_date,$_allowed)
{
if ((isDate($_date)) && (($_allowed!="null") && ($_allowed!=null))){
$allowed_weekdays=json_decode($_allowed);
$weekdays=array();
foreach($allowed_weekdays as $wd){
$weekday=date("l",date("w",strtotime($wd)));
array_push($weekdays,$weekday);
}
if(in_array(date("l",strtotime($_date)),$weekdays)){return TRUE;}
else {return FALSE;}
}
else {return FALSE;}
}
/////////////////////////////
$date="21.05.2010"; //actually is Friday (5)
$wd="[0,1,2]"; //Sunday,Monday,Tuesday
if(dateIsAllowedWeekday($date,$wd)){echo "$date is within $wd weekday values!";}
else{echo "$date isn't within $wd weekday values!"}
I have input dates formatted as "d.m.Y" and an array returned from database with weekday numbers (formatted as 'Numeric representation of the day of the week') like [0,1,2] - (Sunday,Monday,Tuesday).
The returned string from database can be "null", so i check it too. Then, the isDate function checks whether date is a date and it is ok.
I want to check if my date, for example 21.05.2010 is an allowed weekday in this array. My function always returns TRUE and somehow weekday is always 'Thursday' and i don't know why...
Is there any other ways to check this or what can be my error in the code above? thx

I'm not sure why you feel the need to convert the numeric day of the week into a string (eg "Sunday") as you only return a boolean value in the end; anyway I've removed that part and the below code should function as expected:
function dateIsAllowedWeekday($_date,$_allowed)
{
if ((isDate($_date)) && (($_allowed!="null") && ($_allowed!=null)))
{
$allowed_weekdays = json_decode($_allowed);
if (in_array(date("w", strtotime($_date)), $allowed_weekdays))
{
return TRUE;
}
}
return FALSE;
}
Tested with 21.05.2010 (returns false), and 11.05.2010 (returns true), with your allowed_weekdays as above ([0,1,2]).

If you got PHP5.3 running already, you can also do:
function date_validWeekday($format, $date, array $weekdays) {
return in_array(
DateTime::createFromFormat($format, $date)->format('w'),
$weekdays);
}
var_dump(date_validWeekday('d.m.Y', '21.05.2010', array(0,1,2))); // FALSE
var_dump(date_validWeekday('d.m.Y', '11.05.2010', array(0,1,2))); // TRUE

The reason why it keeps returning Thursday is because you are using strtotime() on single digit integer:
$weekday=date("l",date("w",strtotime($wd)));
One of the two things is happening, thought I'm not sure which:
the function interprets the integer as an epoch timestamp, or
the function is returning false, which the date function gets as a 0.
In either case, you are within 10 seconds of the original Epoch start time:
Thu, 01 Jan 1970 00:00:00 GMT
Which is on a Thursday.

function dateIsAllowedWeekday($_date,$_allowed){
if ((isDate($_date)) && (($_allowed!="null") && ($_allowed!=null))){
return in_array(date("w",strtotime($_date)),json_decode($_allowed));
}
return false;
}

Related

How to return TRUE with time()?

How to return TRUE when an account was created more than 30 days ago?
I have the following date:
$udata['joined']; - record date in time():
I tried like this
If($udata['joined'] = strtotime ("+30 days", time())){
return true;
}
Any idea why it's not working correctly?
Return empty.
I guess you want
If timestamp is smaller than (or exactly) 30 days ago
if ($udata['joined'] <= strtotime("-30 days", time()) {
return TRUE;
}
(you need to substract 30 days from now and remove all syntax errors)
You are assigning a value instead of using an operator, i.e. you are using = instead of ==. Try this:
If($udata['joined'] == strtotime ("+30 days", time())){
return true;
}
Edit
As others pointed out, checking for equality will most likely always return false anyway, because you'd be very luck to hit the exact same timestamp!
What you are looking for is the <= (less than or equal) operator to check if $udata['joined'] is a timestamp before 30 days ago. In other words :
// true if the provided date is before 30 days ago
return strtotime($udata['joined']) < strtotime("-30 days", time());

PHP preg_match year validation 1900 to 2019

I'm trying to validate a date in dd-mm-yyyy format, where the year should be between 1900 to 2019.
The day and month part work fine, but i'm failing with the year part. Can you pls help?
$date="31-12-2020";
if (preg_match("/^(0[1-9]|[1-2][0-9]|3[0-1])-(0[1-9]|1[0-2])-(19[0-9]{2}|20([0-1]|[0-9]){2})$/",$date)) {
echo 'True';
return true;
} else {
echo 'False';
return false;
}
This is complete script that you need; function will return true or false if given date is in range:
http://sandbox.onlinephpfunctions.com/code/c0e8108319a24ae5ecf993bb940e1f30aab53fc7
$start_date = '01-01-1900';
$end_date = '01-01-2019';
$date_from_user = '01-01-2018';
check_in_range($start_date, $end_date, $date_from_user);
function check_in_range($start_date, $end_date, $date_from_user,$format='d-m-Y')
{
// Convert to timestamp
$start_ts = DateTime::createFromFormat($format,$start_date);
$end_ts = DateTime::createFromFormat($format,$end_date);
$user_ts = DateTime::createFromFormat($format,$date_from_user);
// Check that user date is between start & end
return (($user_ts >= $start_ts) && ($user_ts <= $end_ts));
}
Your current year part 20([0-1]|[0-9]){2} for handling years 2000 to 2019 just needs little modification to make it correct. Third digit in year part can only be 0 or 1 hence it can be written as [01] and fourth digit can be any hence can be written as [0-9] and that gives us 20[01][0-9]. Following is your modified regex you can use,
^(0[1-9]|[1-2][0-9]|3[0-1])-(0[1-9]|1[0-2])-(19[0-9]{2}|20[01][0-9])$
Demo
Also, since you're just validating your text, you can convert all groups as non-capturing groups to make it little better performance wise.
^(?:0[1-9]|[1-2][0-9]|3[0-1])-(?:0[1-9]|1[0-2])-(?:19[0-9]{2}|20[01][0-9])$
Demo with non-capturing group
This think year expression should as below
19[0-9][0-9] | 20[0-1][0-9]

Php, how to determine if a string is a time?

I want to detect if a string is a time (00:18:31). I know about strtotime() but it also detects "now" as OK, and so on. I need a real solution.
Try this:-
if (DateTime::createFromFormat('H:i:s', $yourtimeString) !== FALSE) {
echo "it's a date";
}else{
echo "it's not a date";
}
Input:- 00:18:31 Output:- it's a date
Input:- now,NOW,now(),NOW() Output:- it's not a date
The validateTime() function checks whether the given string is a valid time. using DateTime class and createFromFormat() static method.
function validateTime($time, $format = 'H:i:s'){
$t = DateTime::createFromFormat($format, $time);
return $t && $t->format($format) === $time;
}
// Returns true
echo var_dump(validateTime("00:18:31"));
echo var_dump(validateTime("23:59:59"));
echo var_dump(validateTime("00:02:30"));
// Returns false
echo var_dump(validateTime("31:18:31"));
echo var_dump(validateTime("24:00:00"));
echo var_dump(validateTime("23:60:60"));
Explanation of $t->format($format) === $time
is a test to check if the time is indeed a real time or not. for instance 23:59:59 is valid time but 24:00:00 is not.
We all know that 23:59:59 is the max acceptable Human time. and 24:00:00 is not. However, We can pretend it means the next day at 00:00:00. that is what DateTime::createFromFormat do! when we give it a time exceed the maximum. It accept it by adding the remaining time to the next day.
For example
today is 2021-05-14 23:59:59
and time to check if we give it to createFromFormat is 24:02:30 the date becomes next day 2021-05-15 00:02:30
We notice that 24:02:30 != 00:02:30. So from that we can summarize that is not valid time. To be valid it must be the same!

strtotime not working in php for HH:MM:SS format

I have a duration like this: 211:30:24. I have to compare whether it's greater than other duration like 01:00:00. I am using strtotime function to change duration into int and then comparing it.
But the problem is strtotime(211:30:24) is returning false. Up to 24:00:00, it's working fine.
I am using below code:
$duration = strtotime('211:30:24');
if($duration >= strtotime ( '01:00:00' )){
return true;
}else{
return false;
}
$duration is false.
I am using php5.1. Anybody have idea why it's happening.
Please go through
http://www.php.net/manual/en/datetime.formats.time.php
the time you specified is not valid, valid time format is mentioned in the document

$var is valid unix timestamp

I need a function to validate if the content of a variable is a valid unix timestamp.
I've checked this thread: Check whether the string is a unix timestamp but the problem is that the function in the most voted answer still can cause some errors, for eg:
function is_timestamp($timestamp)
{
return ((string) (int) $timestamp === $timestamp)
&& ($timestamp <= PHP_INT_MAX)
&& ($timestamp >= ~PHP_INT_MAX);
}
// Some tests:
$timestamp = 1289216307;
var_dump(is_timestamp($timestamp));
var_dump(date('Y-m-d', $timestamp));
// result
bool(false)
string(10) "2010-11-08"
$timestamp = '20101108';
var_dump(is_timestamp($timestamp));
var_dump(date('Y-m-d', $timestamp));
// result
bool(true)
string(10) "1970-08-21"
Here, the first should be TRUE and the second should be FALSE so, what's the best way to test if a $var is a real valid unix timestamp?
Here, the first should be TRUE and the second should be FALSE
Why? 20101108 is a valid UNIX timestamp, - as you say, it's August 21, 1970. Could well be a person's birthday for example.
The only way to achieve what you want is to set a range of dates that mark a "sane" timestamp by the definition you are working with - e.g. anything after January 1st, 2000 - and do a check against that.
A workaround for this would be to check if strtotime recognises the string as a valid date string.
function is_timestamp($timestamp)
{
return ((string) (int) $timestamp === $timestamp)
&& ($timestamp <= PHP_INT_MAX)
&& ($timestamp >= ~PHP_INT_MAX)
&& (!strtotime($timestamp));
}
This will weed out strings that are probably date strings rather than timestamps. It is probably easier to code than writing your own sanity checks.
You can check unix timestamp format using regular expression when your timestamp is bigger than size of integer:
/**
* Check if timestamp is in unix format.
*
* #param string $timestamp
* Target timestamp that will be checked.
*
* #return bool
* TRUE if timestamp is in unix format. FALSE on failure.
*/
function is_unix_timestamp($timestamp) {
return preg_match('/^\d+$/', $timestamp);
}
Write your own ;)
Some things you could check:
Is the given parameter an int? if not => false
Is it negative or above max? => false
Everything else is true
This would work for your given tests.
Any number is potentially a timestamp. The only significant difference between your two examples is that the latter case is a string. In which case:
function is_timestamp($timestamp) {
return is_int($timestamp) || is_float($timestamp);
}
(is_numeric is no good as it also returns true for strings that can be parsed as numbers.)

Categories