php date offset - php

This is my issue, i have a time stamp coming from php, the servers time is 3 hours off from mine. I have offset the time by three hours but quickly realized that at 2 am the date part of the time stamp reads the day before date (day and month) and that does not change till 3 am. This is an issue because the date is important and i need it to be accurate. I have tried the timezone change but cant seem to get it to work. I live in ohio so thats the time i need and the timezone the server is in is three hours behind. So one of two things can help me, a timezone change that works or offsetting the day by 3h, not only the time. Here is my current code:
$timechange = mktime(date("g")+3, date("i"), 0, date("m"), date("d"), date("y"));
$date = date("D, d M Y g:i",$timechange);

$now = new DateTime('now', new DateTimeZone('America/Ohio')); // whatever your TZ's name happens to be
$now->setTimeZone('America/ServerTZ'); // reset to your server's TZ
$datestr = $now->format('D, d M Y g:i'); // get TZ's time as a nice string
By doing the setTimeZone, you affect the OUTPUT of the function - internally the timestamp is unchanged.

Instead of adjusting the times yourself, try just setting the timezone beforehand.
See http://php.net/manual/en/function.date-default-timezone-set.php

Related

Facebook SDK returning incorrect times for events

I have a website that displays events from the website owner's Facebook page. A few weeks ago, someone noticed that the event times are showing up wrong on the website, but they've been correct for a couple years. So basically I'm trying to figure out what the problem is.
Here's an example
Event X has a start time timestamp of 2017-12-18T17:00:00-0500. That date is correct, and that time - 1700, or 5:00 - is the correct time.
So I have this code to convert the timestamp to something I can display
$start_time = date('g:i a', strtotime($event['start_time']));
This returns a time of 10:00 PM
I have the same problem with the end time not converting correctly.
I'm using this code to convert the date (using the same timestamp above):
$start_date = date('l, F j, Y', strtotime($event['start_time']));
This returns the correct date, which confuses me even more because if the date converts correctly, how does the time not convert correctly?
Can someone please help me get the time to convert so I can get these events back on the website?
It is different timezone problem.
You have a datetime with timezone -05:00 but, date('P') output, your server timezone is +00:00. You can use DateTime class to convert the datetime to the timezone your desired.
// convert time to datetime instance
$timestamp = strtotime($event['start_time']);
$datetime = new DateTime;
$datetime->setTimestamp($timestamp);
// set timezone to US/Eastern, Eastern Standard Time (EST), UTC -5
$datetime->setTimezone(new DateTimeZone('US/Eastern'));
// output datetime format
$datetime->format('g:i a');
$datetime->format('l, F j, Y');

php giving wrong answer when using time zone Australia/Sydney

I am developing an website to run in Australia.
so i have set the time zone as follows.
date_default_timezone_set('Australia/Sydney');
I need to calculate number of days between two dates.
I found a strange behavior in the month of October.
$now = strtotime('2013-10-06'); // or your date as well
$your_date = strtotime('2013-10-01');
$datediff = $now - $your_date;
echo floor($datediff/(60*60*24));//gives output 5, this is right
$now = strtotime('2013-10-07'); // or your date as well
$your_date = strtotime('2013-10-01');
$datediff = $now - $your_date;
echo floor($datediff/(60*60*24));//gives output 5, this is wrong, but it should be 6 here
after 2013-10-07 it always give one day less in answer.
Its fine with other timezones. May be its due to daylight saving. But whats the solution for this.
Please help.
Thanks
Why it says 5, and why this is technically correct
In Sydney, DST begins at 2013-10-06 02:00:00 - so you lose an hour in dates straddling that.
When you call strtime, it will interpret the time as a Sydney time, but return a Unix timestamp. If you converted the second set of timestamps to UTC, you'd get a range from 2013-09-30 14:00:00 to 2013-10-06 13:00:00, which isn't quite 6 days, so gets rounded down to 5.
How to get the time difference ignoring DST transitions
Try using DateTime objects instead, e.g.
$tz=new DateTimeZone('Australia/Sydney');
$start=new DateTime('2013-10-01', $tz);
$end=new DateTime('2013-10-07', $tz);
$diff=$end->diff($start);
//displays 6
echo "difference in days is ".$diff->d."\n";
Why does DateTime::diff work differently?
You might ask "why does that work?" - after all, there really isn't 6 days between those times, it's 5 days and 23 hours.
The reason is that DateTime::diff actually corrects for DST transitions. I had to read the source to figure that out - the correction happens inside the internal timelib_diff function. This correction happens if all the following are true
each DateTime uses the same timezone
the timezone must be geographic id and not an abbreviation like GMT
each DateTime must have different DST offsets (i.e. one in DST and one not)
To illustrate this point, here's what happens if we use two times just a few hours either side of the switch to DST
$tz=new DateTimeZone('Australia/Sydney');
$start=new DateTime('2013-10-06 00:00:00', $tz);
$end=new DateTime('2013-10-06 04:00:00', $tz);
//diff will correct for the DST transition
$diffApparent=$end->diff($start);
//but timestamps represent the reality
$diffActual=($end->getTimestamp() - $start->getTimestamp()) / 3600;
echo "Apparent difference is {$diffApparent->h} hours\n";
echo "Actual difference is {$diffActual} hours\n";
This outputs
Apparent difference is 4 hours
Actual difference is 3 hours

Understanding date processing with strtotime

I'm trying to get my head round someone else's code which they've written for handling the dates of when news stories are published. The problem has come up because they are using this line -
$date = strtotime("midnight", strtotime($dateString));
to process a date selected using a jquery calendar widget. This works fine for future dates, but when you try to use a date which is in the previous calendar year, it uses the current year instead. I think this is due to "midnight" finding the closest instance of the selected day and month.
I could remove the "midnight", but I'm not sure what the repercussions of this would be - is there a reason that the midnight could be there?
EDIT: this is the full block of code which handles the date. The date contains the time, which allows the user to publish an item at a specific time.
$array['display_date'] = '24 October, 2011 17:30';
$string = $array['display_date'];
$dateString = substr($string, 0, -5);
$timeArray = explode(':', substr($string, -5));
$hours_in_secs = 60 * 60 * $timeArray[0];
$mins_in_secs = $timeArray[1];
$date = strtotime("midnight", strtotime($dateString));
$timestamp = $date + $hours_in_secs + $mins_in_secs;
//assign timestamp to validation array
$array['display_date'] = $timestamp;
echo $array['display_date']; // Output = 1351094430 (Oct 24 2012 17:00:30)
This really depends on what $dateString contains. Assuming your jQuery widget delivered the time portion as well, your colleague likely wanted to remove the time portion. Compare the following:
echo date(DATE_ATOM, strtotime('2010-10-01 17:32:00'));
// 2010-10-01T17:32:00+02:00
echo date(DATE_ATOM, strtotime("midnight", strtotime('2010-10-01 17:32:00')));
// 2010-10-01T00:00:00+02:00
If your widget doesnt return the time portion, I dont see any reason for setting the date to midnight, because it will be midnight automatically:
echo date(DATE_ATOM, strtotime('2010-10-01'));
// 2010-10-01T00:00:00+02:00
Note that all these are dates in the past and they will result in the given year in the past, not the current year like you say. If they do in your code, the cause must be somewhere else.
Will there be repercussions when you change the code? We cannot know. This is just one line of code and we have no idea of any context. Your unit-tests should tell you when something breaks when you change code.
EDIT after update
The codeblock you show makes no sense whatsoever. Ask the guy who wrote it what it is supposed to do. Not only will it falsely return the current year for past years, but it will also give incorrect results for the minutes, e.g.
24 March, 2010 17:30 will be 2012-03-24T17:00:30+01:00
I assume this was an attempt at turning 24 March, 2010 17:30 into a valid timestamp, which is in a format strtotime does not recognize. But the approach is broken. When you are on PHP5.3 use
$dt = DateTime::createFromFormat('d F, Y H:i', '24 March, 2010 17:30');
echo $dt->format(DATE_ATOM); // 2010-03-24T17:30:00+01:00
If you are not on 5.3 yet, go through https://stackoverflow.com/search?q=createFromFormat+php for alternate solutions. There is a couple in there.

Timestamp Troubles

I have a snippet of code where I want to show the date and time for every time a client uses a discount card. Clients can not have more than two entries per card. However, when I try to display the two entries with the appropriate formatting only the older timestamp formats properly. Code below:
Last Used:
<?php
$timestamp = mysql_to_unix($row->trans_date); //MySql Time stamp 2011-05-31 12:49:59
date_default_timezone_set('America/Chicago'); //Push timestamp ahead 2 hours
$lastuse = date('F j, Y # g:i A', $timestamp); //format date
echo $lastuse;
?>
<?php endforeach; ?>
I have two timestamps coming in 1306871399 and 1306864204. The first stamp successfully processes as May 31, 2011 # 2:49 PM, but the second comes out May 31, 2011 # 12:50 PM.
I am not understanding why only one of the timestamps are being processed. Your feedback is appreciated.
1306871399
- 1306864204
------------
= 7195
7195 seconds = 1hr 59 minutes 55 seconds
May 31/2:49pm -> May31/12:50pm is about 1hr 59 minutes apart
So what's the problem?
You should format your timestamp values for user-display at the MySQL level, instead of using PHP to format them. That way, you don't have to worry about what timezone your PHP server is on (your reference to the Chicago timezone). Try using the MySQL Date Format function to return a MySQL formatted timestamp as a string you can display...
My thinking is that the older timestamp is not being passed through the timezone push, as it is 2 hours behind. Make sure your code is running both values through it.
If that's not it.. has your hosting provider changed recently? Server-time vs. Local-time could be an issue?

One hour difference in date and time after adding Daylight Saving Time offset in php

HI All,
I'm trying to match today's date and time at Atalanta to a database value. I'm testing following code.
$date = new DateTime();
$newToday = $date->format('Y-m-d H:i:s');
$dateTimeArr = split(" ",$newToday);
$dateArr = split("-", $dateTimeArr[0]);
$timeArr = split(":",$dateTimeArr[1]);
$testTime = date("Y-m-d H:i",mktime($timeArr[0]+4, $timeArr[1], $timeArr[2], $dateArr[1], $dateArr[2], $dateArr[0])); // 4 is Daylight Saving Time offset
When I run the code, I found that there is 1 hour time difference if I check the time at http://www.timetemperature.com/tzga/atlanta.shtml
I'm adding the day light saving offset which 4 hours, but still the time I get is 1 hour more than the actual time. Why this difference is seen ? How to rectify this ?
EDIT
My server is at different time zone than Atalanta. I want to handle the time difference without knowing the timezones. For this, for each city we have added timezone offset in database.
Use the DateTime and DateTimeZone objects:
//EDT = Eastern Daylight Saving Time
$x = new DateTime(null, new DateTimeZone('EDT'));
echo $x->format("Y-m-d H:i")
I think that if you use America/New_York (which is in the same timezone as Atlanta) as the timezone, it will change accordingly between normal and daylight saving time.
$x = new DateTime(null, new DateTimeZone('America/New_York'));
echo $x->format("Y-m-d H:i")
Both versions output the same time for me.
Have you checked your server's (the computer that executes the actual PHP script) time? See if it has the right time

Categories