I'm trying to print a specific mesasge to the browser depending if my timestamp is AM or PM. In this instance if it's before 12 noon then then I want to echo out Good morning.
The time stamp held in $person['StartDateTime'] is 2019-10-09T14:00:00
The message always prints out the good morning message and I've tried the other posts on here but can't seem to get it to work. I've tried 'noon', 12, 12 PM, etc..
if ($person['StartDateTime'] < strtotime("noon"))
{
echo 'Meeting Time:' . $person['StartDateTime'] . '<br>';
echo "Good morning" . '<br>';
}
Edited:
If I try as suggested below I get nothing back.
if (strtotime($person['StartDateTime']) < strtotime("noon"))
If I try using after >
if (strtotime($person['StartDateTime']) > strtotime("noon"))
I get the message but also on my morning timestamp - 2019-10-09T10:00:00 which I shouldn't.
I'm wondering do I need to specify noon for the day of the timestamp?
Ok after trying a few things the solution in this case was simple.
Format the date using only "A", this will return AP or PM depending on the time.
$starttime = date("A",strtotime(date($person['StartDateTime'])));
if ($starttime == "AM"){
echo "Good Morning" . '<br>';
}
I suggest using Datetime with proper format argument a which gives either am or pm depending on the time
if ((new Datetime($person['StartDateTime']))->format('a') == 'am') {
// am
} else {
// pm
}
strtotime return timestamp. You compare int value with string. Read about strtotime function
Related
I'm trying to do a comparison between date & times in Carbon PHP 2. For context, my server is in Europe/London timezone, and a user has the functionality to set their own timezone, thus my $timezone variable. My Laravel 8 project default timezone config is Europe/London too.
When a user provides a start time, I store the date & time as a date field in my DB, but obviously the day, month and year would always be wrong at the point my code runs, thus why we override these with the current day.
Still though, you can see from my output that their time is greater than the start time, but my if statement never runs, why?
$timezone = 'Asia/Tokyo';
$startTime = Carbon::parse('2022-08-01 05:00:00');
$theirTime = Carbon::parse(Carbon::now())->setTimezone($timezone);
$ourTime = Carbon::parse($theirTime)->setTimezone('Europe/London');
$startTime = $startTime->day($theirTime->day);
$startTime = $startTime->month($theirTime->month);
$startTime = $startTime->year($theirTime->year);
echo "their time: $theirTime ----- start: $startTime";
if ($theirTime >= $startTime) {
echo 'run now';
} else {
echo 'do not run';
}
output is:
their time: 2022-08-05 05:16:27 ----- start: 2022-08-05 05:00:00do not run
05:16:27 is greater than 05:00:00 so should output run now, what am I missing?
You can use carbon gte() method
if ($theirTime->gte($startTime)) {
echo 'run now';
} else {
echo 'do not run';
}
as for why it says "do not run", it is because "2022-08-05 05:16:27 GMT+1" comes before "2022-08-05 05:00:00 GMT" and carbon carbon converts itself to integer (unix timestamp) in the comparisation.
I cant give you a complete example because you did not define what $timezone is in your question.
If you want to compare the times as strings directly (and have total faith in your control of timezones you can
if ($theirTime->format('H:i:s') >= $startTime->format('H:i:s')) {
echo 'run now';
} else {
echo 'do not run';
}
Ideally you would run the server in UTC. When the user enters Wake me up at 6am you need to know 6am in what timezone, so need to store the timezone with the 6am or with that user's profile - whatever makes more sense in your application. But it would be a problem to search the database for each user's wakeup time in their own timezone so for activities like this, convert the time to UTC before storing it.
Then if the user wanted waking at 6am, this might be 18:00 utc but that would not matter. When the 'wakeup' time is the same as the server's current time, wake the user up and tell them "this is your $wakeup)->tz($user->timezone) wakeup".
Regarding your specific situation, you want to know if now() in Tokyo is greater than the time on the DB record, however you can only look at the H:m in the stored value;
$theirTime = Carbon\Carbon::parse('2022-03-01 05:00'); // get this from DB
// our reference point
$current = now()->tz('Asia/Tokyo');
$target = now()->tz('Asia/Tokyo');
$target->hour = $theirTime->hour;
$target->minute = $theirTime->minute;
$target->second = 0;
if($current->gte($target)) {
echo 'overdue';
} else {
echo 'Not due';
}
Here is a query that i am using to compare time in codeigniter
$present_time = date("h:i a");
$this->db->where('status!=', 'closed ');
$this->db->where('one_hour_break!=', ' ');
$this->db->where("(one_hour_break ='$present_time' or one_hour_break < '$present_time')");
$query = $this->db->get('student');
$final_time = $query->result();
if($final_time)
{
echo "true";
}
else
{
echo "false";
}
It is comparing the time properly if it is between 1 and 12 however it is not comparing time properly between the given time is between 12pm to 1pm and 12am to 1pm
e.g :
So if present time: 12:30 pm and one_hour_break: 1:30 pm, then one hour break should be greater than present time, and the result should say false, however it is saying true. Same goes with the time between 12pm to 1pm
Can anyone please tell how to manage this issue
There are a few ways to fix this, the best way is to go back and store the times in the database with "Y-m-d H:i" or something like it.
That way you can get a fixed timestamp of when, and not only time of day which is useless most of the times when you develop.
Then you use strtotime() http://php.net/manual/en/function.strtotime.php to convert the date in string format to a numeric value that can easily be compared.
Using WIndows, XAMPP 5.6.8 I am building a simple web app in HTML and PHP.
I would like to compare a date retrieved from a database with today's date.
I have a function that successfully returns a string value (in the UK date format d-m-y).
My code so far is;
$expDate = get_api_data($id); // returns a string
var_dump($expDate); // this prints string(8) "31-12-19"
Using this $expDate value I would like to achieve something like;
if (strtotime('d-m-y', $expDate) > time()) { // if date > than today
echo 'date is greater than today';
}
elseif (strtotime('d-m-y', $expDate) < time()) { // if date < than today
echo 'date is less than today';
}
else {
echo 'date not found';
}
Currently I am receiving date is less than today - even though the date is 31-12-19. I'm not sure if I am approaching this the correct way?
Any help would be greatly appreciated as I have alreday spent a lot of time researching answers to no avail.
I got this error when executing your code
PHP Notice: A non well formed numeric value encountered
You should look at the doc in order to make a good usage of this function: http://php.net/manual/fr/function.strtotime.php
The first param should be a time, not a format.
By the way, i prefer use DateTime class to compare dates, you can do:
<?php
$expectedDate = \DateTime::createFromFormat('d-m-y', get_api_data($id));
$nowDate = new \DateTime();
if ($expectedDate > $nowDate) { // if date > than today
echo 'date is greater than today';
}
elseif ($expectedDate < $nowDate) { // if date < than today
echo 'date is less than today';
}
else {
echo 'date not found';
}
$formattedDate = DateTime::createFromFormat('d-m-y', $expDate);
$expDate= $formattedDate->getTimestamp();
if ($expDate > time()) { // if date > than today
echo 'date is greater than today';
.....
Try above code sample, try to use DateTime class if you have PHP 5.2.0 or higher http://php.net/manual/en/datetime.createfromformat.php . Then using that dateTime object you can do comparisons in a way you want e.g. in my sample I am doing it by time.
Your code will show a notice. if you turn on the php error reporting, you will observer it.
I've been doing a good amount of research with this, and used a few codes to get to know how to make this work, but nothing has worked the way I wanted it to, or hasn't worked at all.
The code is:
<?php
$time1 = $user['last_active'];
$time2 = "+5 minutes";
if (strtotime($time1) > strtotime($time2)) {
echo "Online!";
}else{
echo "Offline!";
}
?>
It is supposed to compare the two variables, and find out if the last active variable is greater or less than 5 minutes, and if it is greater, appear offline. I do not know what's wrong as the NOW() updates on each page and stops if the user is not logged in. Any suggestions or help? Thanks.
The $time1 variable is coming from a fetched array that gets the ['last_active'] information that updates on each page.
I fixed my code, but it still doesn't work right, however, I think I have managed to get further than I was..
<?php
$first = new DateTime();
$second = new DateTime($user['last_active']);
$diff = $first->diff( $second );
$diff->format( '%H:%I:%S' );
if($diff->format( '%H:%I:%S' ) > (strtotime("5 minutes"))){
echo "Offline";
}else{
echo "Online";
}
?>
What can I do at this point?
Nobody pointed out that you actually have a bug. The "current time" will never be greater than "the current time +5 minutes"
Your first code sample will work right if you instead use "-5 minutes" as the "online threshold."
Also, comparing a timestamp without date to the output of strtotime() as you do in the second code is not a proper comparison. It has two problems:
Each time a new day comes around, the same time value will be repeated.
The output of strtotime is an integer representing seconds-since-epoch; the output of format() is a textual representation of hours:minutes:seconds within the current date.
As for your question how to calculate time between 2 dates / time, please view the solution on the following posts, that should give you enough information! (duplicate ? )
Calculate elapsed time in php
And here
How to get time difference in minutes in PHP
EDIT AS YOU PLEASE
<?
$first = new DateTime(); // this would hold your [last active]
//$first->modify("-6 minutes");
$second = new DateTime("NOW");
$difference = $second->diff( $first ); // second diff first
if ($difference->format('%i') > 5) { // comparing minutes only in example ( %i )
echo "The user is AFK";
} else {
echo "user might still be active";
}
?>
What PHP code can I use to stop showing text at a certain time?
For example:
"Come to this event at 3PM on Monday!"
I don't want that to show after 3:01PM on the site.
First, you have to know the date and time of Monday 3pm, in a format that can be understood by PHP functions : 2010-04-26 15:00:00
Then, you have to convert that to an UNIX timestamp, which can be done with the strtotime() function :
$tsMonday = strtotime(2010-04-26 15:00:00);
After that, the time() function gives you the current timestamp ; which means you can use it to determine whether monday 3pm has passed or not :
if (time() < $tsMonday) {
echo "not yet monday 3pm";
}
Note : instead of converting the date to a timestamp with strtotime each time the page is called, you could directly put the timestamp value in your code -- if this is only for one event, it'll work great (but, for several events, it might become harder to maintain).
<?PHP
$when = strtotime('April 26, 2010 15:00:00');
if ($when > time()){
echo "Be there at 3pm on monday or be square";
}
$endTime = 1272319200; // The timestamp you want the message to stop displaying
if ( time() < $endTime){
echo "Come to this event at 3PM on Monday!";
}
else{
echo 'It\'s too late to show this message.';
}