PHP need set date based on time - php

I have an simple question about how to set date based on time range. This is my code so far:
date_default_timezone_set("Asia/Jakarta");
$time = date("G:i");
if ($time >= 8:00)
{
echo date("j-F-Y");
}
else
{
echo date("j-F-Y", time() - 60 * 60 * 24);
}
Example today is 29-Apr-2013.
Now I want before time 8:00 the date will still 28-Apr-2013. After that, date will continue to 29-Apr-2013.
The code is successfully complete the rule, if time before 8:00. But if I changed my computer time to be 11:00 or etc, it will set yesterday back.

$time = date("G:i");
if ($time >= 8:00)
This comparison is not good. Try numerically like
$time = intval(date("Gi"));
if ($time >= 800)

Related

Expiration date for some database entries

I am trying to set an expiration on DB entries. I've set the field to datetime and entered some values manually through MySQL
I take the value from the table and convert it to strtotime(). then I get the current time using strtotime("now"); or time(); they seemed to return the same value.
I then take the future date(the one from the db) and with if statement check if its smaller then current time if so I set it as expired. if it's still bigger then current time I return how much time left..
Here is the code for that:
$time_left = "";
$value['ex_date'] = '2012-11-22 18:17:33';// this is whats in the DB now.
$future_time = strtotime($value['ex_date']);
$now_time = strtotime('now');
if($deal_end < $now_time){
$time_left = 'Expired';
}else{
$seconds = $future_time - $now_time;
$days = floor($seconds / 86400);
$seconds %= 86400;
$hours = floor($seconds / 3600);
$seconds %= 3600;
$minutes = floor($seconds / 60);
$seconds %= 60;
if($days >= 1) {$time_left .= "D:$day ";}
if($hours >= 1) {$time_left .= "H:$hours ";}
if($minutes >= 1) {$time_left .= "M:$minutes ";}
if($seconds >= 1) {$time_left .= "S:$seconds ";}
For some reason the above doesn't work well. its like there is some time gap.
my question is: is there a way to check server time vs database time ?
because the strtotime('now'); time seems different then current timestemp by like 2/3 hours for some reason.
I can suggest two other approaches:
a. Select from the database rows that did not expire yet adding the logic to the query itself
b. run cron/mysql schedule every minute that will clear the database entries that had expired
SELECT * from TABLE where X = Y and NOW() < expiredField
Besides, PHP has a built in class just for the operations with date you are trying to perform.
It's called DateTime.
$dt = new DateTime('2012-11-22 18:17:33');
$dtNow = new DateTime();
$interval = $dtNow->diff($dt); // php.net/DateInterval
if($interval->invert)
echo 'expired';
else
echo $interval->format('%m month, %d days, %h hours, %s seconds');
To your original question
Checking the server time is
echo time();
Checking database time is
SELECT NOW();
You can find server(linux) time zone using following at command line:
$ date +%Z
Or following in php:
$ echo system('date +%Z');
In php you can use date_default_timezone_get function.
Most probably your system and php timezones will be different.
You can change php timezone by using date_default_timezone_set function.
In-case anyone is curious about how i solved it:
$result = mysql_query("select CURRENT_TIMESTAMP;");
$row = mysql_fetch_array( $result );
$DB_now = $row['CURRENT_TIMESTAMP'];
$deal_end = strtotime($value['ex_date']);
$now_time = strtotime($DB_now);
I just use database's current timestamp as "now"
Not sure if that's the best solution but it works

Midnight time issue

I am having problem detecting if the shop is still open or closed after midnight.
On Tuesday ($weekday = 2), shop open from 6 PM to 1:30 AM (after midnight)
Assume current time is 01:05 AM
$weekday = 2;
//Convert current time to minutes (01:05)
$currentTime = ($weekday - 1) * 1440 + "01" * 60 + "05";
//Current Week Day
$shopOpenTime = "18:00";
$shopCloseTime = "01:30";
$open = explode(':', $shopOpenTime);
$close = explode(':', $shopCloseTime);
//Convert to Minutes;
$MinutesOpen = (($weekday - 1) * 1440) + ($open[0] * 60 + $open[1]);
$MinutesClose = (($weekday - 1) * 1440) + ($close[0] * 60 + $close[1]);
if ($MinutesClose < $MinutesOpen)
$MinutesClose += 60 * 24;
if (($currentTime >= $MinutesOpen) && ($currentTime < $MinutesClose)) {
echo "Shop Is Open";
} else {
echo "Shop Is Close";
}
What is the solution to fix this issue?
Honestly this entire chunk of code should be re-written. The logic is doomed because your $weekday parameter is comparing the same day for $currentTime as $minutesOpen. You added 24 hours to $minutesClose to push it to (technically Wed), now that comparison is correct. It says Closed because you haven't moved $currentTime up 24 hours into wed.
So if you were to just read this in english you're comparing 1:30am on Tuesday (which is right after monday night) against 6:30 pm on Tuesday, and this fails (this is because of the $weekday parameter is set to tuesday in the $currentTime).
Without seeing how you populate your $weekday parameter, I'm guessing that when you actually run this code being poplated with say the date() function, at 12:01 (on tuesday) it's going to increment to wed, then you're code will be populating open and close time with wed's hours, which is going to be off too.
I'm sorry I know this isn't a solution saying to re-write the entire logic, but it's going to be massively flawed in a production environment.
If you just want to make it work, staying with the mindset/context of 'tuesday' you have to reflect current time in tuesday's sense, and thats with 25:05 meaning 1:05 on wed, and not 01:05 tuesday for the second time. That keeps the context correct and it works.
$currentTime = ($weekday - 1) * 1440 + "25" * 60 + "05";
You are comparing the current time to the opening period that will begin on the current time's day. But the shop is currently open due to an opening period that started yesterday. Just compare with yesterday's period also:
if ((($currentTime >= $MinutesOpen - 1440) && ($currentTime < $MinutesClose - 1440)) || (($currentTime >= $MinutesOpen) && ($currentTime < $MinutesClose))) {
But beware, this works only, if the shop opens / closes every day at the same time.

How to calculate the time difference between unix time stamps?

I am creating time stamps in PHP using time();
I have the $current_time and $purchase_time. How do I make sure that purchase_time is less than 24 hours of current time?
If they are UNIX timestamps, then you can calculate this by yourself really easy, as they are seconds.
$seconds = $current_time - $purchase_time
$hours = floor($seconds/3600);
if ($hours < 24){
//success
}
Since UNIX timestamps are just numbers of seconds, just use the difference:
$purchasedToday = $current_time - $purchase_time < 24 * 60 * 60;
if ($purchasedToday) {
echo 'You just bought the item';
} else {
echo 'You bought the item some time ago';
}
You can construct a DateTime object and then use it's diff() method to calculate the difference between $current_time and $purchase_time:
$currentTime = new DateTime();
$purchaseTime = new DateTime('2011-10-14 12:34:56');
// Calculate difference:
$difference = $currentTime->diff($purchaseTime);
if ($difference->days >= 1) {
echo 'More than 24 hours ago.';
}
This is more reliable than calculating the difference yourself, as this method takes care of timezones and daylight saving time.
Something like this:
$difference=time() - $last_login;
I had use something like this:
<?php
if(date("U", strtotime("-24 hours", $current_time) > date("U", $purchase_time)) {
echo "More then 24 hours you purchased this radio";
}
?>
This works even if the time stamp not is a UNIX-timestamp.

Converting user's day and time to server's day and time in php

I have a scenario in which the user selects a time and day (or multiple days) and that value must be converted to whatever that day and time would be in UTC time. I have the gmt offset amount for each user (the users set it when they signup). For instance:
A user in the eastern timezone selects:
3:15 pm, Monday, Tuesday, Friday
I need to know what time and days that information would be in UTC time. The solution has to take into situations such Monday in one timezone can be a different day in UTC time. Also, if the time can be converted to 24 hour format, that would be a plus.
For the sake of clarity, something along the lines of an array should be returned such as:
Array('<3:15 pm eastern adjusted for utc>', '<Monday adjusted for UTC>', '<Tuesday adjusted for UTC>', '<Friday adjusted for UTC>');
I don't need the result to be directly formatted into an array like that - that's just the end goal.
I am guessing it involves using strtotime, but I just can't quite my finger out how to go about it.
$timestamp = strtotime($input_time) + 3600*$time_adjustment;
The result will be a timestamp, here's an example:
$input_time = "3:15PM 14th March";
$time_adjustment = +3;
$timestamp = strtotime($input_time) + 3600*$time_adjustment;
echo date("H:i:s l jS F", $timestamp);
// 16:15:00 Monday 14th March
EDIT: kept forgetting little things, that should be working perfectly now.
Made a function to do the job:
<?
/*
* The function week_times() converts a a time and a set of days into an array of week times. Week times are how many seconds into the week
* the given time is. The $offset arguement is the users offset from GMT time, which will serve as the approximation to their
* offset from UTC time
*/
// If server time is not already set for UTC, uncomment the following line
//date_default_timezone_set('UTC');
function week_times($hours, $minutes, $days, $offset)
{
$timeUTC = time(); // Retrieve server time
$hours += $offset; // Add offset to user time to make it UTC time
if($hours > 24) // Time is more than than 24 hours. Increment all days by 1
{
$dayOffset = 1;
$hours -= 24; // Find out what the equivelant time would be for the next day
}
else if($hours < 0) // Time is less than 0 hours. Decrement all days by 1
{
$dayOffset = -1;
$hours += 24; // Find out what the equivelant time would be for the prior day
}
$return = Array(); // Times to return
foreach($days as $k => $v) // Iterate through each day and find out the week time
{
$days[$k] += $dayOffset;
// Ensure that day has a value from 0 - 6 (0 = Sunday, 1 = Monday, .... 6 = Saturday)
if($days[$k] > 6) { $days[$k] = 0; } else if($days[$k] < 0) { $days[$k] = 6; }
$days[$k] *= 1440; // Find out how many minutes into the week this day is
$days[$k] += ($hours*60) + $minutes; // Find out how many minutes into the day this time is
}
return $days;
}
?>

Calculate the difference between date/times in PHP

I have a Date object ( from Pear) and want to subtract another Date object to get the time difference in seconds.
I have tried a few things but the first just gave me the difference in days, and the second would allow me to convert one fixed time to unix timestamp but not the Date object.
$now = new Date();
$tzone = new Date_TimeZone($timezone);
$now->convertTZ($tzone);
$start = strtotime($now);
$eob = strtotime("2009/07/02 17:00"); // Always today at 17:00
$timediff = $eob - $start;
** Note ** It will always be less than 24 hours difference.
Still gave somewhat wrong values but considering I have an old version of PEAR Date around, maybe it works for you or gives you an hint on how to fix :)
<pre>
<?php
require "Date.php";
$now = new Date();
$target = new Date("2009-07-02 15:00:00");
//Bring target to current timezone to compare. (From Hawaii to GMT)
$target->setTZByID("US/Hawaii");
$target->convertTZByID("America/Sao_Paulo");
$diff = new Date_Span($target,$now);
echo "Now (localtime): {$now->format("%Y-%m-%d %H:%M:%S")} \n\n";
echo "Target (localtime): {$target->format("%Y-%m-%d %H:%M:%S")} \n\n";
echo $diff->format("Diff: %g seconds => %C");
?>
</pre>
Are you sure that the conversion of Pear Date object -> string -> timestamp will work reliably? That is what is being done here:
$start = strtotime($now);
As an alternative you could get the timestamp like this according to the documentation
$start = $now->getTime();
To do it without pear, to find the seconds 'till 17:00 you can do:
$current_time = mktime ();
$target_time = strtotime (date ('Y-m-d'. ' 17:00:00'));
$timediff = $target_time - $current_time;
Not tested it, but it should do what you need.
I don't think you should be passing the entire Date object to strtotime. Use one of these instead;
$start = strtotime($now->getDate());
or
$start = $now->getTime();
Maybe some folks wanna have the time difference the facebook way. It tells you "one minute ago", or "2 days ago", etc... Here is my code:
function getTimeDifferenceToNowString($timeToCompare) {
// get current time
$currentTime = new Date();
$currentTimeInSeconds = strtotime($currentTime);
$timeToCompareInSeconds = strtotime($timeToCompare);
// get delta between $time and $currentTime
$delta = $currentTimeInSeconds - $timeToCompareInSeconds;
// if delta is more than 7 days print the date
if ($delta > 60 * 60 * 24 *7 ) {
return $timeToCompare;
}
// if delta is more than 24 hours print in days
else if ($delta > 60 * 60 *24) {
$days = $delta / (60*60 *24);
return $days . " days ago";
}
// if delta is more than 60 minutes, print in hours
else if ($delta > 60 * 60){
$hours = $delta / (60*60);
return $hours . " hours ago";
}
// if delta is more than 60 seconds print in minutes
else if ($delta > 60) {
$minutes = $delta / 60;
return $minutes . " minutes ago";
}
// actually for now: if it is less or equal to 60 seconds, just say it is a minute
return "one minute ago";
}

Categories