Time Zones in PHP, Date, MySQL...? - php

I am trying to figure out how to display time in PST on my php site.
I have been putting in timestamps in the MySQL Database with NOW() and calling them like this:
date("m/d/y g:i a", strtotime($ref['lastupdated']))
However, the server time is in Central and However, as the website is geared towards people in the PST time zone. Basically it needs to show in PST. Is there a way I could do this - like, take that value and subtract 2 or something? Any ideas?
I'm not sure also if I need to go about this the PHP route or if the problem, rather, could be solved via MySQL.
Any ideas are appreciated - thanks!
$query = "SELECT refid, CONCAT(fname,' ',lname) refname, email, street, city, state, zip, interestlvl, status, added, lastupdated FROM referrals WHERE affid='$affid' ORDER BY added DESC;";
$result = mysql_query($query) or die("Query Failed: ".mysql_errno()." - ".mysql_error()."<BR>\n$Query<BR>\n");
if ($result) {
while ($ref = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo '
<td bgcolor="#EFEFEF" class="list">'.
date_default_timezone_set('America/Chicago');
$date = new DateTime($ref['lastupdated']);
$date->setTimezone(new DateTimeZone('America/Los_Angeles'));
$date->format('m/d/y g:i a')
.'</td>';
}
}

$date = new DateTime($ref['lastupdated']);
$date->setTimezone(new DateTimeZone('America/Los_Angeles'));
echo $date->format('m/d/y g:i a');
given that PST is America/Los Angeles. You have to make sure that date.timezone is set to the correct timezone for Central. This can either be accomplished via the php.ini or via date_default_timezone_set().
The code then treats your incoming string $ref['lastupdated'] as being in the default timezone (Central) and converts the date-time into the *America/Los_Angeles* timezone.

Related

How to return timestamp based on user timezone?

Say that I have a timezone variable which is returned from a database that my users can set to their prefered time zone. GMT+5 would return simply as:
$timezone = 5;
I need the users timezone so that I can reflect the date of an event in their particular time format. Here is what I have so far:
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$time = strftime("%Y-%m-%d %I:%M %p", strtotime($row["time"]));
}
echo $time;
How could I change the above output to reflect the time of the event based on the users preferred time zone?
//Output = 2017-01-15 12:09 AM
//Expected Output: 2017-01-14 07:09 PM
Use the DateTime and DateTimeZone objects.
<?php
$storedDate = new DateTime('2017-01-15 12:09 AM');
$userDate = (clone $storedDate)->setTimeZone(new DateTimeZone('Europe/Paris'));
printf(
"Stored Date:\t%s\nUser Date:\t%s\n",
$storedDate->format(DATE_ATOM),
$userDate->format(DATE_ATOM)
);
// outputs:
// Stored Date: 2017-01-15T00:09:00+00:00
// User Date: 2017-01-15T01:09:00+01:00
As said in my comment, I dot not advise to store the timezone as an integer.
First, because some timezone can't fit an integer, for example India is up to 5:30 (+0530) from the UTC time.
Storing as integer also won't help you to properly handle summer time in some countries, or even in some region in a same country (see Brazil).
Timezone offset are subject to change, but defined configuration for a given location such as Europe/Paris are likely not.

How i can convert datetime to unix time stamp and compare it with other timestamp in php?

I have one page in that I have two textboxes where user will enter unix timestamp and datetime, I have to compare that both timestamp and datetime but in php the timezone giving different timestamp as per time zone so the code doesn't working in all places where time zones are different.
Please help on this I had used..
strtotime(),mktime(),getTimestamp() in php,
also used my sql for this..
SELECT UNIX_TIMESTAMP() but all are giving different time stamps.
$sql = "SELECT UNIX_TIMESTAMP('date time from text box') as timeStampfromdb";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$timeStampFromDateTime = $row["timeStampfromdb"];
}
if($timeStampFromDateTime == timestamp textbox value)
{
matched
}
else
{
not matched
}
You can set php timezone in php.ini file, for GMT you need "GMT".
You can also try in your code:
echo date('Y-m-d H:i:s T', time()) . "<br>\n";
date_default_timezone_set('GMT');
echo date('Y-m-d H:i:s T', time()) . "<br>\n";
time() should return the current unix timestamp.
If you are working with dates and times across time zones you should work with everything in GMT to avoid time zone issues. If you need to display a date and time at some point that is the place to do any time zone conversion that may be necessary.

How to convert a date time to a users time zone in PHP

I have a date time entered in the timezone UTC+0 and in the format
$curDate = date("Y-m-d");
$curTime = date("g:i a");
What I want is, detect the timezone of the visiting user.
After that convert the date and time into his/her time zone and show the date time in their timezone.
$utc_date = DateTime::createFromFormat(
'Y-m-d G:i',
'2011-04-27 02:45',
new DateTimeZone('UTC')
);
$acst_date = clone $utc_date; // we don't want PHP's default pass object by reference here
$acst_date->setTimeZone(new DateTimeZone('Australia/Yancowinna'));
echo 'UTC: ' . $utc_date->format('Y-m-d g:i A'); // UTC: 2011-04-27 2:45 AM
echo 'ACST: ' . $acst_date->format('Y-m-d g:i A'); // ACST: 2011-04-27 12:15 PM
You could use http://ipinfodb.com/ to detect users localization and as a result users timezone, for instance:
function geoLocalization($ip, $api_key)
{
$params = #file_get_contents("http://api.ipinfodb.com/v2/ip_query.php?key=".$api_key."&ip=".$ip."&timezone=true");
$fields = #new SimpleXMLElement($params);
foreach($fields as $field => $val) {
$result[(string)$field] = (string)$val;
}
return $result;
}
as you get users localization you can use date_default_timezone_set to set the timezone.
It is good practice to let your users to overwrite this.
You can find all timezones on this site:
http://php.net/manual/en/timezones.php
For php +5.3 you can use DateTime::createFromFormat. But for previous versions of php, You should use of strtotime(). here is a example:
$curDate = date('l, F d y h:i:s');
$curDate = strtotime($curDate);
$new = date('Y-m-d H:i:s', $curDate);
Either force the user to provide you the timezone as the very first thing.
Or
Gets request's IPAddr, then geolocation, then tmezone.
The second option is dependent upon 3rd party libraries and 3rd part servers.

How to compare EST date time with mysql data

I have purchase data in mysql database table. All data on server are stored in UTC timezone.
I can convert date-time in EST timezone using below code.
$date = date_create(date('Y-m-d H:i:s'), timezone_open('Etc/GMT+0'));
date_timezone_set($date, timezone_open('Etc/GMT+5'));
I am getting last and next Saturday of current day using below code.
$dt_week_start_time = strtotime("last saturday")+((20*3600)+ 1);
$dt_week_start_date = date('Y-m-d G:i:s', $dt_week_start_time);
$dt_week_end_time = $dt_week_start_time + (7*3600*24) - 1;
$dt_week_end_date = date('Y-m-d G:i:s', $dt_week_end_time);
But how can i compare above EST timezone converted date-time with mysql data stored in UTC timezone? I need to convert data of 'purchasedatetime' field in EST timezone when I fire below query. Is this possible? Or am I doing it in wrong way? Please advise.
$str_query_select = "SELECT *, SUM(extendedprice) AS gross_price FROM t_product_purchase ";
$str_query_select .= " WHERE purchasedatetime BETWEEN '".$dt_week_start_date ."' AND '".$dt_week_end_date."'";
$str_query_select .= " AND sellerpkid=1";
$str_query_select .= " GROUP BY purchasedatetime ORDER BY purchasedatetime DESC ";
You can see this:
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_convert-tz
or
SET time_zone = 'proper timezone';
being done once right after connect to database. and after this all timestamps will be converted automatically when selecting them.
in php you can do this:
$date = new DateTime($dt_week_start_date);
$date->setTimezone(new DateTimeZone('Europe/Moscow')); // based on your required zone
echo $date->format('Y-m-d H:i:s');
then use it in your sql.

PHP/MySQL: Convert from YYYY-MM-DD to DD Month, YYYY?

I have in a MySQL table a DATE column that represents the date in this format: YYYY-MM-DD.
I wanto to retrieve the date from the database using PHP but display it like this: DD Month, YYYY.
From '2009-04-13' to '13 April, 2009' for example.
Witch is the best way to do it?? ( I know how to get the date from the DB. I only need to know how to convert it)
I also need to display the month names in Spanish. There is a way to do it without translating each month using strplc or something like that??
I'm new to programming, please be detailed.
Thanks!!!
Refer to DATE_FORMAT() function in MySQL. I guess that's the best way for you to do it.
Also, you can make this:
Fetch your date from DB
Use strtotime in PHP, to convert to unix time
Then format the time using date.
By using date() you'll be able to get months names in Spanish when you set your locale in PHP with setlocale.
You could also skip the strtotime() part by using UNIX_TIMESTAMP(date) in your MySql select. But remember that this is a MySQL specific function and may not be be portable in the future.
Execute following MySQL queries:
SET lc_time_names = 'es_ES';
SELECT DATE_FORMAT(t.date,'%e de %M, %Y') FROM your_table t ...
With MySQLi it'll be:
$mysqli->query("SET lc_time_names = 'es_ES'");
$stmt = $mysqli->prepare("SELECT DATE_FORMAT(t.date,'%e de %M, %Y') FROM your_table t ...where id = ?");
...
Another option not yet mentioned:
SQL:
SELECT UNIX_TIMESTAMP(date) FROM table
PHP:
print date('your format', $timestamp_from_the_db);
Personally, I like to use integer data types in MySQL for date storage in the UNIX timestamp format. I leave all the processing of that integer up to PHP. Keeping tables and queries as simple as possible has always served me well. Predominantly, in the code I write, dates have some sort of calculation done to them. This is all done on the PHP side and always in the UNIX timestamp format. Storing or retrieving the dates in anything other than the UNIX timestamp format just means another step for errors to creep in and makes the query less modular. How a date is formatted is best left up until the last minute before it's displayed. It's just my opinion, but unless there are extreme circumstances where you can't process the DB value after extraction, a date shouldn't be formatted SQL-side.
A simplified example:
<?php
$date = now();
$dueDate = $date + 60*60*24*7; // One week from now
$sqlInsert = "INSERT INTO reports SET `dueDate` = $date";
$resInsert = mysql_query( $sqlInsert );
$sqlSelect = "SELECT `dueDate` FROM reports";
$resSelect = mysql_query( $sqlSelect );
$rowSelect = mysql_fetch_array( $resSelect );
$DB_dueDate = $rowSelect['dueDate'];
$daysUntilDue = ( $DB_dueDate - now() ) / 60*60*24;
$formattedDueDate = date( "j F, Y", $DB_dueDate );
?>
The report is due on <?=$formattedDueDate?>. That is <?=$daysUntilDue?> from now.
Simplest way is to use the strtotime() function to normalize the input to UNIX timestamp.
Then use the date() function to output the date in any format you wish. Note that you need to pass the UNIX timestamp as the second argument to date().
This will help you to convert as you want:
$dob ='2009-04-13';
echo date('d M Y', strtotime($dob));
$origDate = "2018-04-20";
$newDate = date("d-m-Y", strtotime($origDate));
echo $newDate;

Categories