How do I compare current time to a preset time in PHP? - 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
}

Related

True only on Weekdays and at a specific time

I am using PHP 7.4.1 and Laravel Framework 6.20.12 with the carbon library.
I want to return true only once from Monday to Friday if a date crosses the $sendPost variable. My cron-job runs every 5 Minutes.
I tried:
<?php
require 'vendor/autoload.php';
use Carbon\Carbon;
function checkMsgFired() {
$now = Carbon::now();
// $now = Carbon::createFromFormat('d/m/Y H:i:s', "19/1/2021 14:43:00");
$lastSendPost = Carbon::createFromFormat('d/m/Y H:i:s', "18/1/2021 14:43:00"); // the posting has already happended today
$post = array();
$post['Frequency'] = "MoToFr"; // send only from monday to friday at a specific date once
$post['sendPost'] = Carbon::createFromFormat('H:i:s', "14:40:00"); // when the post should be send
if($post['Frequency'] === "MoToFr") {
// if it is a WEEKDAY
if($now->dayOfWeek !== Carbon::SATURDAY or $now->dayOfWeek !== Carbon::SUNDAY) {
// $lastPosting didn't happen today
if(!$lastSendPost->isToday() && $now->gt($post['sendPost'])){
return true;
}
else{
return false;
}
} else {
return false;
}
}
}
var_dump(checkMsgFired());
However, the posting time does not seem to work. How can I check that the event has already fired once at the exact time?
Furthermore, is there an easier version to code this?
I appreciate your replies!
Something like possibly? This’ll give you true when the time is between 14:40 and 14:45, so long as your cron job runs every 5 minutes it should be mostly correct.
<?php
require 'vendor/autoload.php';
use Carbon\Carbon;
function checkMsgFired() {
$now = Carbon::now();
$frequency = "MoToFr";
$sendPost = Carbon::createFromFormat('H:i:s', "14:40:00");
if ($frequency === "MoToFr") {
if ($now->isWeekday()) {
return $now->between($sendPost, $sendPost->addMinutes(5));
}
}
return false;
}
var_dump(checkMsgFired());

How to properly compare datetime with timezone with current time

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.

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..

Add current time to database and when reading it later check if that time has passed

So I'd like to add the current time to the database, to a specific user when he does something, and later on read it, and check if that time has passed (by checking current time and substracting that from the one in database; to check if it has passed or not)
So how would I do this? I tried with something like this:
$date = date("YmWjis");
$calculate = $date - $info['lastvisit'];
if($calculate <= -1)
{
echo "you need to wait before visiting again"; // (just an example)
} else {
//do something
}
I also tried both:
!$calculate < 0
$calculate < 0
etc. But I can't get it to work. Can anyone help me? :P
edit for Parag;
$date = date("YmWjis");
$dote = date("YmWjis") + $time; // ($time is set earlier and is 30 seconds)
echo "wait " . $date = $date - $dote . " seconds until next visit";
work?
It says like "wait 20138269786674 seconds until next visit".
You can try something like this:
$dateDiff = new DateTime("2014-04-27 22:00:15");
$date = new DateTime();
$diff = $date->diff($dateDiff);
if($diff->invert == 0)
{
echo "you need to wait before visiting again"; // (just an example)
} else {
//do something
}
$db_time = "2014/04/28 15:15:15";
$cur_time = "2014/04/28 18:15:15";
if(strtotime($cur_time) > strtotime($db_time))
{
// Current time exceeds DB time
$diff = date('Y/m/d H:i:s', strtotime($cur_time)-strtotime($db_time));
echo $diff;
}
else
{
// Current time didn't exceeds DB time
}
UPDATE
$date = strtotime(date("YmWjis"));
$dote = strtotime(date("YmWjis")) + $time; // ($time is set earlier and is 30 seconds)
echo "wait " . $date = $date - $dote . " seconds until next visit";
DEMO
http://3v4l.org/LBIXu
Don't use a database. This does the job without the db overhead. It uses PHP sessions.
<?php
session_start();
if (!isset($_SESSION['lastVisitTime'])) {
$_SESSION['lastVisitTime']=new DateTime();
} else {
$now=new DateTime();
if ($_SESSION['lastVisitTime']->diff($now) > $someMaxValueYouDefine) {
echo "You must wait before visiting again.";
}
}

Validating timezone 'name' coming in from different site?

i've got users coming in from a different site and i'm getting that site to send across their timezone in a standard 'tz' format
Antarctica/Casey Antarctica/Davis
Antarctica/DumontDUrville Antarctica/Macquarie
Antarctica/Mawson Antarctica/McMurdo
How do i verify that this 'string' coming in is a VALID timezone entry?
this is what i'm doing
$script_tz = date_default_timezone_get();
if(!date_default_timezone_set($specifiedTimeZone))
{
date_default_timezone_set($script_tz);
$errormessage = "Invalid TimeZone";
return;
}
date_default_timezone_set($script_tz);
but i dont like it - seems kludgy.
testing it out:
Test1
$test1 = 'America/New_York';
$test2 = 'junk';
$start = microtime(true);
for($i=1;$i<10000;$i++)
{
if (in_array($test1, DateTimeZone::listIdentifiers())) {}else {}
if (in_array($test2, DateTimeZone::listIdentifiers())) {}else {}
}
$end = microtime(true);
echo $end-$start;
?>
9.7208099365234
Test2
<?php
$test1 = 'America/New_York';
$test2 = 'junk';
error_reporting(0);
$start = microtime(true);
for($i=1;$i<10000;$i++)
{
$script_tz = date_default_timezone_get();
if(!date_default_timezone_set($test1))
{
date_default_timezone_set($script_tz);
}
else
date_default_timezone_set($script_tz);
$script_tz = date_default_timezone_get();
if(!date_default_timezone_set($test2))
{
date_default_timezone_set($script_tz);
}
else
date_default_timezone_set($script_tz);
}
$end = microtime(true);
echo $end-$start;
?>
0.25762510299683
use DateTimeZone::listIdentifers()
if (in_array($timezone, DateTimeZone::listIdentifiers())) {
echo "valid";
}
else {
echo "invalid";
}
Validate against the tz database. There's http://code.google.com/p/tzdata/, that claims to provide the tz database in PHP format (whatever this means).
Check out this: How to check is timezone identifier valid from code?
Report different approaches to solve your problem.
There is a helper: timezone_identifiers_list() will return an array of strings of timezones. then you can use something like in_array to validate it.
if (in_array($timezone, timezone_identifiers_list())) {
// valid
}
You could take the list of supported timezones, save it in a file and compare what you're getting to the list:
http://php.net/manual/en/timezones.php

Categories