How to properly compare datetime with timezone with current time - php

I need to revalidate cache if its expired. My cache data looks like this
$cacheData['valid_until'] = "2017-11-23T12:00:00+00:00" //string
I wonder how to properly compare if current dateTime is smaller then $cacheData['valid_until'], while taking into consideration also timezone...
This is my current code
private function checkCacheValidation($cacheData) {
$now = (new DateTime());
$cacheTime = (new DateTime($cacheData['valid_until']));
if ($now < $cacheTime) {
die('Cache is valid, no need to request new data');
return true;
} else {
die('cache not valid, get new data');
return false;
}
}
Can somebody please check if i'm doing this right way? Do you suggest any other solution?
If you need any additional informations, please let me know and i will provide... Thank you

As you can see in the following topic, you can compare DateTime variables:
$d1 = new DateTime('2008-08-03 14:52:10');
$d2 = new DateTime('2008-01-03 11:11:10');
var_dump($d1 == $d2);
var_dump($d1 > $d2);
var_dump($d1 < $d2);
Giving the result of:
bool(false)
bool(true)
bool(false)
So seems like a working solution.

Related

Function to check user birth date is 18 years or upper not always work correctly

I am beginner webdeveloper.
I use in my project Laravel 5.8.
I have this this code:
if ($this->calcutateAge($request->input('date')) < 18) {
return Redirect::back()->withErrors(['You are a minor. Registration is allowed for adult users']);
}
function calcutateAge($dob)
{
$dob = date("Y-m-d", strtotime($dob));
$dobObject = new DateTime($dob);
$nowObject = new DateTime();
$diff = $dobObject->diff($nowObject);
return $diff->y;
}
It's work fine. But I have problem with date ex 2045-12-12.
This function is not working. With year: 2015-12-12 - it's okey.
How can I repair it?
I suggest you should use Carbon.
use Carbon\Carbon;
function calcutateAge($dob){
return \Carbon::parse($dob)->age;
}
I would write your function to return true or false depending on if the user is 18 or not.
function is_18($dob)
{
$dobObject = new DateTime(date("Y-m-d", strtotime($dob)));
$nowObject = new DateTime();
return $dobObject < $nowObject ? ($dobObject->diff($nowObject)->y > 18) : false;
}
Then your IF block is simplified to this:
if (!$this->is_18($request->input('date')) {
return Redirect::back()->withErrors(['You are a minor. Registration is allowed for adult users']);
}
I would find out when a person born 18 years ago was born, then compare to that:
function isAdult($dob) {
$adult = new DateTime('18 years ago'); // 'date' => '2002-09-01 12:05:52.000000'
$dob = date("Y-m-d", strtotime($dob));
$dobObject = new DateTime($dob);
return $adult >= $dobObject; // 2002-09-01 is after the passed date of birth
}
you can add 18 year and compare the date like this:
$dobObject = new DateTime($dob.' +18 years');
$nowObject = new DateTime();
if ($dobObject > $nowObject)
print 'great you are granted'
else
print 'sorry you are minor'
If you run var_dump($diff); you will see:
["invert"]=> int(1)
Which means is a negative difference.
So, you can do return $diff->invert? -$diff->y : $diff->y;
Of course this is a solution based on your code. You can always check if the date is someday into the future, and return false or throw some exception in this case.

How do I compare current time to a preset time in PHP?

I want PHP to check if it's 8:30 AM and if it is, I want it to change a variable.
I tried,
$eightthirtyam = "08:30:00";
if(time() >= strtotime($eightthirtyam )){
$refresh = true;
}
But the boolean doesn't change. Any idea what I did wrong?
strtotime depends on the time zone.. so you should define timezone too.
You should set your default timezone before comparing.
http://php.net/strtotime
Example:
date_default_timezone_set('America/Los_Angeles');
$eightthirtyam = "08:30:00";
if(time() >= strtotime($eightthirtyam )){
$refresh = true;
}
http://codepad.org/GC0VA7nw
The function time() returns always timestamp that is timezone independent (=UTC), while strtotime() give a local time, So there is a timezone offset.
You need to subtract the timezone offset form the local time, before the compare, and check the live demo for a good understanding.
In php we have new DateTime function. So you can use this to match your date as give below example
$refresh = false;
$eightthirtyam = "08:30:00";
$date = new DateTime();
if($date->format('H:i:s') == $eightthirtyam)
{
$refresh = true;
}
Here is an example
$refresh = "false";
$eightthirtyam = "08:30:00";
$date = new DateTime("2017-06-07 8:30:00"); // suppose your system current time is this.
if($date->format('H:i:s') == $eightthirtyam)
{
$refresh = "true";
}
echo $refresh;
You can check answer by executing on online php editor http://www.writephponline.com/
Try above example, I think this may help you.
$hr= date('H:i');
if(strtotime($hr)==strtotime(08:30) ){
$refresh = true;
}
Please try this way. It will work i your case.
This will help you:
date_default_timezone_set('Asia/Kolkata');
$eightthirtyam = "08:30:00";
$refresh = false;
if(strtotime(date('H:i:s') == strtotime($eightthirtyam )){
$refresh = true;
}
Reference:-/ strtotime
the code is fine untill i know. but still if you want to do some actions, you can do something like this.
$refresh=false;
$eightthirtyam = "08:30:00";
if(time() >= strtotime($eightthirtyam ))
{
$refresh = true;
}
if($refresh)
{
//your statement is true do something here
}
else
{
//false statement
}

PHP - how to validate if current time is matched with given timezone start and end

How can i make current date/time validate with given timezone/start/end?
outside $meeting_for, $meeting_starts till $meeting_ends range, all should return false.
$meeting_for = 'America/Los_Angeles';
$meeting_starts ='2016-10-11 00:00:00';
$meeting_ends = '2016-10-11 06:00:00';
function give_meeting_result_based_on_rightnow() {
// PHP server time
date_default_timezone_set('Europe/Brussels');
$etime1 = date('Y-m-d H:i:s');
$date = new DateTime($etime1, new DateTimeZone('Europe/Brussels'));
// PHP server time converted to meeting time
$date->setTimezone(new DateTimeZone($meeting_for));
$logic_check= $date->format('Y-m-d H:i:s') . "\n";
if($logic_check is between ($meeting_starts till $meeting_ends )) {
return true;
}
else {
return false;
}
}
echo give_meeting_result_based_on_rightnow();
The solution is quite simple, but you made a few mistakes. The variables at the top aren't in global scope. They're not available inside the function. Therefor you either need to put them inside the function, or pass them along as parameters (as I did in the code below). After that it's a very simple check with an if statement:
<?php
// These are NOT global. They're not available within the scope of the function
$meeting_for = 'America/Los_Angeles';
$meeting_starts ='2016-10-11 00:00:00';
$meeting_ends = '2016-10-11 06:00:00';
function give_meeting_result_based_on_rightnow($timeZone, $startTime, $endTime) {
// PHP server time
date_default_timezone_set('Europe/Brussels');
$etime1 = date('Y-m-d H:i:s');
$date = new DateTime($etime1, new DateTimeZone('Europe/Brussels'));
// PHP server time converted to meeting time
$date->setTimezone(new DateTimeZone($timeZone));
$logic_check= $date->format('Y-m-d H:i:s') . "\n";
if ($logic_check >= $startTime && $logic_check <= $endTime)
{
return true;
} else {
return false;
}
}
// Passing along the variables as parameters to the function
echo give_meeting_result_based_on_rightnow($meeting_for, $meeting_starts, $meeting_ends);
?>
Keep in mind that the echo() won't actually give any output. You need to return a string for that instead of a boolean.
EDIT:
$ var_dump_this_code_with_curdate('2016-10-10 07:54:32')
bool(false)

Get time difference & User Information using php

Please, i need to get the time difference between a particular time and the current time. ie. I want to track users who submit an assignment late. the deadline time is 10:00AM everyday.I have surf,but all the solution i am seeing does not seems to work. see below:
<?php
$d1 = new DateTime(date('Y-m-d 10:00:00'));//Deadline time
$d2 = new DateTime(date('Y-m-d H:i:s'));//Submission time
$interval = $d1->diff($d2);
$c = $interval->minute;
if($c>0){
echo "submitted late";}else{ echo "Submitted on time";}
?>
Regarding the first point, your code doesn't work because $interval->minute is always positive. So you should simply compare two dates.
Use the following code to achieve it:
$d1 = new \DateTime(date('Y-m-d 10:00:00'));//Deadline time
$d2 = new \DateTime(date('Y-m-d H:i:s'));//Submission time
if($d1 < $d2) {
echo "submitted late";
} else {
echo "Submitted on time";
}
$deadline = date('10:00:00');
$now = date('H:i:s');
if($now > $deadline){
echo "submitted late";
} else {
echo "Submitted on time";
}
as simple as that

how to format hours in php?

I made this function and it works:
$myHour = "09:09";
$myHour = time_format($myHour);
function time_format($h){
$initial_string = $h;
$new = substr($h,1,strlen($h));
$h = substr($h,0,-4);
if ($h == "0"){
return $new;
}else{
return $initial_string;
}
}
This function verify it the string looks like: "01:02" and get rid of the first "0", so it will become "1:02" else if it looks like "13:13" it will return "13:13".
My question is how to improve my function? or if there exists other better method ? thx
use ltrim to just simply remove the leading 0 if there is one. I assume there is a reason you cant just change the date format which generates the string ?
function time_format($h){
return ltrim($h, "0");
}
But changing the date format is the best option
this will be your shortened function, still readable
function time_format($h){
if (substr($h, 0, 1) == "0"){
return substr($h, 1);
}else{
return $h;
}
}
this would be even shorter
function time_format($h){
return substr($h, 0, 1) == "0" ? substr($h, 1) : $h;
}
this one is even without the if operators
to read more about it, here is a link.
<?php
$date = new DateTime('2000-01-01');
echo $date->format('Y-m-d H:i:s');
?>
Please have a detailed look here:
http://www.php.net/manual/en/datetime.format.php
You can get a DateTime object by UnixTimestamp (if needed) with this way
$dtStr = date("c", $timeStamp);
$date = new DateTime($dtStr);
Source: Creating DateTime from timestamp in PHP < 5.3
use PHP date function
try to google first..

Categories