Hello i am learning php i tried to use the date function to display the current time.
I have an if statement to check the current time whether it is greater than the next hour.
Here is the code
<?
$current_time= date('G:i:s');
$next_time= date('G:i:s',strtotime('+1hour'));
if($current_time > $next_time )
{
echo $current_time." is greater than ".$next_time;
}
?>
At the time of writing this code it was 9:23:39
and the next hour should have been 10:23:39
Surprisingly i got :
9:23:39 is greater than 10:23:39
Am i missing something here.
Please help
Keep in mind you are comparing strings, not numbers. 9 is greater than 1 and therefore returns true.
Either use the DateTime class to do this, or compare the unix timestamps (time() and strtotime('+1hour'))
you could use a integer to work the if statement
$var = date("U",timestamp)
to get the number of Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) thus giving you a number which you can determine which one is greater.
Related
I have a script that uses an if statemnt based on date('H')
if (date('H') >= 16) { do this}
98% of the time this works correctly.
On some submissions (date('H') > 16) it fails, if statment not fired.
Where does this value come from, is there anything from an individual users PC that can affect it?
I have tried modifying the system clock with no difference, no idea why some of these are failing.
Returns a string formatted according to the given format string using
the given integer timestamp or the current time if no timestamp is
given. In other words, timestamp is optional and defaults to the value
of time().
Well you could check with time() what value is currently handled.
Do to your problem:
Everything that is before 4pm will fail since the condition goes falsey.
date outputs the current server time formatted in the timezone set by date_default_timezone_set. If you're getting unexpected values from it, you may be globally setting the timezone somewhere which changes the output:
date_default_timezone_set('UTC');
echo date('H'); // 15
date_default_timezone_set('Asia/Tokyo');
echo date('H'); // 00
What's wrong with my code? I want my script to check if it is Monday and is greater or equal to 22:00 and less than or equal to 23:00.
$t = date("D:G:i");
if ($t >= "Mon:22:00" && $t <= "Mon:23:00") {
$status = "up";
} else {
$status = "down";
}
you cannot compare strings (it is not dates, it is just strings of arbitrary symbols), as we're not code-writing monkeys I'll just describe how you should do it instead of providing copy-pastable code:
get weekday number, hour, minute from current time into 3 separate variables
compare weekday variable with monday value
if weekdays are ok - compare hours with 22
minutes can be omitted here, if you check for [22, 23), or you need to make additional comparison for 23:00 case
another approach - generate unix timestamps for the closest monday 22 and 23 hours, and then numeric comparisons
You're comparing two strings instead of two numerical values. Not ideal at all. You want to look into converting the dates into a Unix timestamp and comparing those values.
mktime: http://php.net/manual/en/function.mktime.php
mktime will allow you to get a Unix timestamp for any date.
time: http://php.net/manual/en/function.time.php
time will give you the current date and time as a Unix timestamp.
You can then compare to find out which is larger/smaller than the other.
I need to compare two dates to show an edit link if it is within 5 mins after the post was made, in PHP. If more than 5 minutes have passed, don't show anything.
$answer_post_date = get_the_time("Y-m-d");
$current_date = date("Y-m-d");
$formated_current_date = strtotime($answer_post_date);
$formated_answer_post_date = strtotime($current_date);
At this point I have two values:
1274414400 ($formated_current_date)
1276056000 ($formated_answer_post_date)
I am not sure what to do next to check if the current date/time is > 5 mins from the answer post date.
Any suggestions would be great.
All I really need the answer to be is a Boolean (yes/no) and if yes, display the minuets left to show the link to edit.
You're only handling dates, how are you supposed to know if the difference is 5 minutes?
Anyway, I'd say the majority of the PHP code that uses the default PHP functions is at least somewhat broken. The problem is you, despite a unix timestamp storing the correct point in time something happens, it does not store timezone information. See here.
So, forget using only date and strtotime. Use the datetime extension.
Store in the database the Unix timestamp and the timezone (by timezone I mean e.g. Europe/Lisbon). Then:
$tz = new DateTimeZone($timezone);
$answer_post_date = new DateTime("$timestamp");
$answer_post_date->setTimeZone($tz);
$current_date = new DateTime("now", $tz);
$diff = $current_date->diff($answer_post_date);
if ($diff->format("a") > 0 ||
$diff->format("h") > 0 ||
$diff->format("m") >= 5) {
//more than 5 minutes have passed
}
Of course, for comparing dates, you can always compare the timestamps.
My understanding of what you need to do:
$delta = ($formated_current_date - $formated_answer_post_date) / 60; // in minutes
if ($delta < 5) {
// show $delta
}
EDIT: Like others pointed out, this alone will not fix all of the issues at hand. As I see it, the smallest change to your current code would be to use a date format with higher granularity - such as "Y-m-d H:i:s". This being enough, like others pointed out, is contingent on the post's date being in the same timezone as your system.
I don't see the need to do a round-trip to a string format and back, regardless of how efficient or reliable it is.
date() will default to calling time() which you can call directly and get the current time in seconds as a Unix epoch timestamp (which is what you're trying to end up with in $formated_answer_post_date). You need to look in the WordPress docs to find the equivalent based on the post's value.
Then you can do a simple comparison of seconds. 5 minutes is 300 seconds.
You will still need to check that the code can assume the timezones of both values will be the same.
How would I construct a statement like if current time ($time) is more than 30 seconds past time ($djs['currenttime'])? Would it be something like
if ($time => $djs['currenttime'])? I can't figure it out with the 30 seconds..:).
Thanks :).
The 30 seconds you are struggling with it's simply a +30 added on the conditional incrementing the value of $djs['currenttime'].
You can use the time() function to get the actual time. I'm assuming that djs['currenttime'] is a value extracted from the database. Therefore the comparison would be the following:
if(time() > $djs['currenttime'] + 30){
//actions here;
}
time() returns the number of seconds since Jan 1st 1970 00:00:00 GMT so for this to work, the format of the $djs['currenttime'] variable should also be a unix timestamp. If not, you will need to convert one of them to the appropriate format first.
if ($time > ($djs['currenttime'] + 30))
Assumes that both values are actual timestamps and not formatted strings
I'm trying to calculate the number of days between two days, but I'm running into issues with Daylight Savings Time. Here's my code:
function date_diff($old_date, $new_date) {
$offset = strtotime($new_date) - strtotime($old_date);
return $offset/60/60/24;
}
Works fine as long as the days are both within the same DST period:
echo date_diff('3/15/09', '3/18/09'); // 3
But not if they're further apart:
echo date_diff('11/15/08', '3/18/09'); // 122.95833333333
I want an even number of days, and don't care about DST. I suppose I could round the result, but that feels kludgy. Is there a better (easy) way? I don't want to have to write a whole day-parsing-and-counting-avoiding-leap-years thing if I can avoid it.
(Note: this has to run under php 5.1.6, so some of the date features in 5.3 may not be available.)
A bit more info: I'm going to take the offset and add it to other datetimes that are in a db, and I want only the day part to change, not the time part. Turns out rounding won't work, anyway, because when I do the adding it gets off by one hour in the other direction. Maybe there's a better approach to the whole problem....
Force the dates to live into a timezone without Daylight Savings Time, GMT/UTC:
function date_diff($old_date, $new_date) {
$offset = strtotime($new_date . " UTC") - strtotime($old_date . " UTC");
return $offset/60/60/24;
}
echo date_diff('3/15/09', '3/18/09'); // 3
echo date_diff('11/15/08', '3/18/09'); // 123
you could use http://ca3.php.net/date_default_timezone_set to set the timezone to GMT so there will be no offset.
Alternately, you can manually add an offset using the date('I',$timetamp)
if ( date("I") == 1 ) { // "WE ARE MDT";
$timeZone = "MDT";
} else {
$timeZone = "MST";
}
You can force rounding in a specific direction by using floor() or ceil().
I tried the 'UTC' code above. Didnt work for me. I stll got decimal values.
When there is daylight saving date within the date range the difference serial decimal portion will be either under .5 or over. when date range has day light saving going on 3/15 the decimal value is > .5 when daylight is going off date decimal < .5. so I just put the difference serial in a round() function and I get the whole numbers i need for number of days.