Calculating the php current time by timezone - php

Background
I am making some updated to a PHP application that is very old. In the application there was an error being thrown because the use of a depreciated function mktime(). I updated this function across the application with time() instead. Once I did this I noticed that when the local time for a user which is calculated by their zip code is displayed, it is one hour behind the actual local time.
I have tracked the time calculation to a function which is below. The time is passed into the value of, $client["localtime"]
Example Code
if (isset($time) && $time) {
$utc_str = gmdate("M d Y H:i:s", time());
$utc = strtotime($utc_str);
if (isset($tznames[ $time["timezone"] ])) {
$client["timezone"] = $tznames[ $time["timezone"] ];
} else {
$client["timezone"] = "Unknown";
}
if ($time["daylightsavings"] == "Y" && date("I")) {
$time["timezone"]--;
}
$client["localtime"] = date("g:ia", $utc - ($time["timezone"] * 3600));
} else {
$client["localtime"] = "Unknown";
$client["timezone"] = "Unknown";
}
Question
Why is this showing the local time for the client's timezone behind by 1 hour and what must I do to fix it?

if (isset($time) && $time) {
$utc_str = gmdate("M d Y H:i:s", time());
$utc = strtotime($utc_str);
if (isset($tznames[$time["timezone"]])) { $client["timezone"] = $tznames[$time["timezone"]]; }
else { $client["timezone"] = "Unknown"; }
if ($time["daylightsavings"] == "Y" && date("I")) { $time["timezone"]--; }
// print_r(($time["timezone"] * 3600).",".$client["timezone"].",".$time["timezone"].",".$utc_str.",".$utc);
$client["localtime"] = date("g:ia", $utc - ($time["timezone"] * 3600 - 3600));
} else { $client["localtime"] = "Unknown";
$client["timezone"] = "Unknown";}
Check the above code I have subtracted the 3600 from so that it show 1hour late please check if it will work

you can use this function
function convertTimeByTimezone($datetime,$timezone='Asia/Kolkata') {
$given = new DateTime($datetime, new DateTimeZone("UTC"));
$given->setTimezone(new DateTimeZone($timezone));
$output = $given->format("Y-m-d H:i:s");
return $output;
}

You can use this code:
$date = new DateTime("now", new DateTimeZone('Australia/Adelaide'));
echo 'Australia/Adelaide: '.$date->format('Y-m-d H:i:s');
$date1 = new DateTime("now", new DateTimeZone('America/Chicago'));
echo 'America/Chicago: '. $date1->format('Y-m-d H:i:s');

Related

Add 23 hrs 59 minutes as a unix time stamp in PHP

Can someone give me a working example of what my code should be as my efforts are getting me nowhere?
My code currently says have
if (isset($_POST['startdate'])) {
$startdate = DatePickerToTime($_POST['startdate']);
} else {
$startdate = strtotime('today midnight');
}
and
if (isset($_POST['enddate'])) {
$enddate = DatePickerToTime($_POST['enddate']);
} else {
$enddate = time();
}
which works.
However, I want to say if startdate is equal to enddate then add 23 hours and 59 minutes to enddate
I have read the documentation and am trying
if($_POST['$startdate'] == $_POST['$enddate']) {
$_POST['$enddate'] += date("h:i:sa", "23:59:59");
}
but this doesn't work.
$datetime1 = date('2009-10-11 12:30:00');
$datetime2 = date('2009-10-11 12:30:00');
echo "<pre>";
if($datetime1 == $datetime2){
echo "yes";
echo "<br>";
$datetime2 = date("Y-m-d H:i:s", strtotime("+23 hours 59 minutes",strtotime($datetime2)));
echo $datetime1."===================".$datetime2;
}
else {
echo "NO<br>";
echo $datetime1."===================".$datetime2;
}

How to set fix time variables in php?

I want to set a fix time variables in php for my if and else condition.
For example:
$startTime = '08:00:00';
$endTime = '16:00:00';
$totalhrs = $endTime - $startTime;
echo $totalhrs;
Anyone know how to declare the time in PHP?
Thanks for the help
$startTime = strtotime('08:00:00');
$endTime = strtotime('16:00:00');
$totalhrs = ($endTime - $startTime) / 3600;
echo $totalhrs;
you can use datetime object for this case
$startTime = new DateTime('08:00:00');
$endTime = new DateTime('16:00:00');
$totalhrs = $startTime->diff($endTime)->h;
You can try the below function to check timestamps. If you don't pass it a second parameter, it will evaluate if the first time has passed the CURRENT time, otherwise it will compare the first time against the second.
Function timeHasPassed($Time, $Time2 = 0) {
If ($Time2 != 0) {
$Now = new DateTime($Time2);
} Else {
$Now = new DateTime();
}
$Then = new DateTime($Time);
If ($Now > $Then) {
Return TRUE;
} Else {
Return FALSE;
/*
You can also use the below code to print out how long is left until the timestamp has passed. Keep in mind, this will return TRUE if tested as a boolean so maybe consider returning a different datatype instead of TRUE if you decide to go this route.
$Time = new DateTime($Time);
$Now = new DateTime();
$Remainder = $Time->diff($Now);
$Remainder = $Remainder->format("%h hours, %i minutes, and %s seconds!");
return $Remainder;
*/
}
}

PHP timestamp and dates issue

So I have a piece of code on a certain page of my site that does things with timestamps. Pretty much what it does is there is a UNIX timestamp that is placed in the database from each individual Purchase Order. Once a certain amount of time has passed and nothing has been done to that Purchase Order then an indication will begin flashing on the page with the amount of hours that is past due. Once someone takes action then the flashing indication goes away.
Now, everything is working perfectly fine. The issue I am having is that the indicator should only take Monday thru Friday into account. Not the weekends. Also, I've set the hours from 9am to 5pm est but the code seems to 100% skip all these restrictions and just takes all days and times into consideration.
I've placed the code below and as you can see I've set the restrictions of days and time but it seems to be voided somehow. Any help would be much appreciated with this issue.
$current_stardate = time();
$past_stardate = $stardate['time_stamp'];
$placer = ($current_stardate - $past_stardate) / 3600;
$from = date("Y-m-d H:i:s", $current_stardate);
$to = date("Y-m-d H:i:s", $past_stardate);
define('DAY_WORK', 28800); // 9 * 60 * 60
define('HOUR_START_DAY', '09:00:00');
define('HOUR_END_DAY', '17:00:00');
$date_begin = $to;
$date_end = $from;
$d1 = new DateTime($date_begin);
$d2 = new DateTime($date_end);
$period_start = new DateTime($d1->format('Y-m-d 00:00:00'));
$period_end = new DateTime($d2->format('Y-m-d 23:59:59'));
$interval = new DateInterval('P1D');
$period = new DatePeriod($period_start, $interval, $period_end);
$worked_time = 0;
$nb = 0;
foreach($period as $date){
$week_day = $date->format('w'); // 0 (for Sunday) through 6 (for Saturday)
if (!in_array($week_day,array(1, 5)))
{
if ($date->format('Y-m-d') == $d1->format('Y-m-d'))
{
$end_of_day_format = $date->format('Y-m-d '.HOUR_END_DAY);
$d1_format = $d1->format('Y-m-d H:i:s');
$end_of_day = new DateTime($end_of_day_format);
$diff = $end_of_day->diff($d1)->format("%H:%I:%S");
$diff = split(':', $diff);
$diff = $diff[0]*3600 + $diff[1]*60 + $diff[0];
$worked_time += $diff;
}
else if ($date->format('Y-m-d') == $d2->format('Y-m-d'))
{
$start_of_day = new DateTime($date->format('Y-m-d '.HOUR_START_DAY));
$d2_format = $d2->format('Y-m-d H:i:s');
$end_of_day = new DateTime($end_of_day_format);
$diff = $start_of_day->diff($d2)->format('%H:%I:%S');
$diff = split(':', $diff);
$diff = $diff[0]*3600 + $diff[1]*60 + $diff[0];
$worked_time += $diff;
}
else
{
$worked_time += DAY_WORK;
}
}
if ($nb> 10)
die("die ".$nb);
}
$the_work = $worked_time/60/60;
$genesis_stardate = strtotime($stardate['date_purchased']);
if($past_stardate == NULL)
{
$the_work = NULL;
$future_days = NULL;
}
else
{
$future_days = ($current_stardate - $past_stardate) / 3600;
}
$date is not defined. Try to define it, and the problem should be solved.

PHP Day count function writing

I need to Write a function named countDays which takes a single parameter named dateinstring which is string in the form ”MM.DD.YYY” represent a real date value. The function should print to the console the number of days from the beginning of the year specified in dateInString until the date represented in dateInString. If the value of dateInString is invalid, the function should print ”Bad format” to the console.
I have written the code as below :
function countDays($dateInString){
date_default_timezone_set('America/Los_Angeles');
$date = explode('.', $dateInString);
if(count($date) == 3 && checkdate($date[0], $date[1], $date[2])){
$formatted_date = $date[2].'-'.$date[0].'-'.$date[1].'00:00:00';
$diff = strtotime($formatted_date).'-'.strtotime($date[2].'-01-01 00:00:00');
echo round($diff/86400)+1;
}
else {
echo 'Bad format';
}
};
countDays('1.15.2014');
But the above code seems that not giving the correct output. It is about 33% correct. But where is the problem with this code ? Please help me!!!
$diff = strtotime($formatted_date).'-'.strtotime($date[2].'-01-01 00:00:00');
Change to
$diff = strtotime($formatted_date) - strtotime($date[2].'-01-01 00:00:00');
You made the minus symbol a string instead of an operator.
You could try it this way
function countDays($dateInString) {
date_default_timezone_set('America/Los_Angeles');
$date = explode('.', $dateInString);
if (checkdate($date[0], $date[1], $date[2])) {
$year_start = mktime(0, 0, 0, 1, 1, $date[2]);
$your_date = mktime(0,0,0,$date[0], $date[1], $date[2]);
$diff = $your_date - $year_start;
echo floor($diff /(60*60*24));
} else {
echo "Bad date supplied";
}
}
A better approach would be to use the DateTime class. I haven't included the validation in this, but i suggest you use regex for that.
function countDays($dateInString){
$parts = explode('.', $dateInString);
$date = new DateTime($parts[2] . '-' . $parts[0] . '-' . $parts[1]);
$compare = new DateTime( $date->format('Y') . '-01-01' );
$interval = $date->diff($compare);
return $interval->format('%a');
}
echo countDays('09.15.2014');
Check this out.
function countDays($dateInString){
date_default_timezone_set('America/Los_Angeles');
$date = explode('.', $dateInString);
if(count($date) == 3 && checkdate($date[0], $date[1], $date[2])){
$formatted_date = strtotime($date[2].'/'.$date[0].'/'.$date[1]);
$endTimeStamp = strtotime("2014/01/01");
$timeDiff = abs($endTimeStamp - $formatted_date);
echo round(intval($timeDiff/86400));
}
else {
echo 'Bad format';
}
};
countDays('01.01.2014');

Daylight Saving Time (DST) in CakePHP

I'm creating a web application using cakephp 1.2.6. There is a functionality that I need to save the time that user is entered in GMT format. I'm using below method to do this.
function convertDateTimeToGMT($dateTimeStr,$fromTimeZone, $format = 'Y-m-d H:i:s') {
if (empty($dateTimeStr))
return $dateTimeStr;
else if (empty($fromTimeZone))
return $dateTimeStr;
else {
// Inverse the + or minus. Decimal value should be passed
//$timeHelper = new TimeHelper();
$newTZ = -1 * $fromTimeZone;
return $this->format($format, $dateTimeStr, null, $newTZ) ;
}
}
function format($format = 'd-m-Y', $date, $invalid = false, $userOffset = null) {
$date = $this->fromString($date, $userOffset);
if ($date === false && $invalid !== false) {
return $invalid;
}
return date($format, $date);
}
function fromString($dateString, $userOffset = null) {
if (empty($dateString)) {
return false;
}
if (is_int($dateString) || is_numeric($dateString)) {
$date = intval($dateString);
} else {
$date = strtotime($dateString);
}
if ($userOffset !== null) {
return $this->convert($date, $userOffset);
}
return $date;
}
function convert($serverTime, $userOffset) {
$serverOffset = $this->serverOffset();
$gmtTime = $serverTime - $serverOffset;
$userTime = $gmtTime + $userOffset * (60*60);
return $userTime;
}
convertDateTimeToGMT($dateTimeStr,$fromTimeZone, $format = 'Y-m-d H:i:s') is the method that I'm calling in my code to pass the date time and time zone. I have a combo box of time zones and if user select time zone as "Pacific" it will pass the -8 as the value of $fromTimeZone. But because of the DST this can be changed.
So is there any way in cakephp to find the up to date time zone values automatically and convert the time to GMT?
Once you know the timezone of the user you can get its offset as follows:
$est_tz = new DateTimeZone('America/New_York');
$d = new DateTime("now", $est_tz);
$offset = $est_tz->getOffset($d);

Categories