I am trying to have a line of code added to an html document that is preceded by the time. I want the time zone to be relative to me, however I cannot change it from the default UTC. I have changed in the php.ini file to PST as well as using date_default_timezone_set('America/Los_Angeles'); and yet it still prints the time 7 hours ahead of my timezone. Heres the code that deals with the time:
session_start();
if(isset($_SESSION['name']))
{
date_default_timezone_set('America/Los_Angeles');
$msg = $_POST['text'];
$fo = fopen("log.html", 'a');
fwrite($fo, "<div class=msgln>(".date("g:i A").") <b style=color:red;>".$_SESSION['name']."</b>: ".stripslashes(htmlspecialchars($msg))."<br></div>
");
fclose($fo);
}
Servers should be set to UTC, and you should not be looking to change the default. Instead, what you want to do is create a DateTime object based on the time, then convert it to the timezone you want, and display.
$now = new DateTime();
$now->setTimezone(new DateTimeZone('America/Los_Angeles'));
echo $now->format('g:i A');
I don't know if your format string is valid or not, but the format method is suppossed to be compatible with that accepted by the date() function you were using in your original example.
First make sure you're using a valued timezone. You can find a list of supported timezones in the PHP docs.
The second problem is using date() without specifying the timestamp. This defaults to the timestamp produced by time() which (based on a comment in the documentation) is UTC time. You'll either have to use strftime() or manually subtract the difference from UTC.
If you use 'etc/GMT' you can set the dateTime object to the desired time zone like so:
$dtz = new DateTimeZone('etc/GMT-10');
$dt = new DateTime(date("Y-m-d h:i A"), $dtz);
$date = gmdate("Y-m-d h:i A", $dt->format('U'));
Related
I'm trying do execute a php script with cron after 4 hours after saving an record in database. My problem here is not with cron, all here works fine(I'm sure of this because I'm receiving test mails from daemon cron every 4 hours as it should).
The problem is when I calculate the difference between the timestamp, converted to unix, and the current time and then execute some script.
But the diff bewtween these two times are adding 3 hours more to them and I don't know why but my script executes after 7 hours, instead of 4 hours. Can anyone help me please?
My code looks like this:
<?php
require_once('some-path/wp-load.php');
global $wpdb;
$constant= 4*3600;
$table = 'notifications';
$data = $wpdb->get_results("SELECT * FROM $table WHERE status = 'pending'");
$time = time();
foreach ($data as $r){
$temp_data = strtotime($r->date_created);
if ($time - $temp_data > $constant){
$email = $r->email;
$message = 'test';
$subject = 'test';
$headers = 'From: test <test#test.com>' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$mail_client = wp_mail($email, $subject, $message, $headers);
if($mail_client){
$wpdb->update($tabel, array('status' => 'sent'), array('id_raport'=>$r->id_raport), array('%s'), array('%d'));
}
}
}
Example of date from database Using strtotime(): 1458814621, Directly from database "2016-03-24 10:17:01"
Now, I know I can do something like this to get the real localtime:
date_default_timezone_set('Europe/Bucharest');
$date = date('m/d/Y h:i:s a', time());
$time = strtotime($date);
Update.
But this returns the same thing as the time() method.
Now, I know I can do something like this to get the real localtime:
date_default_timezone_set('Europe/Bucharest');
$date = date('m/d/Y h:i:s a', time());
$time = strtotime($date);
A UNIX timestamp is not "local". A UNIX timestamp is the same all over the world. What you're doing in this code is merely converting a timestamp (time()) to a human readable format, and then reinterpreting it into a timestamp; the result is identical to the original time() value (or at least it should be!).
A human readable date/time format, such as you receive from MySQL (2016-03-24 10:17:01) is incomplete without a timezone. There are more than 24 different absolute points in time at which it is "2016-03-24 10:17:01" somewhere in the world. That timestamp by itself doesn't mean very much.
When you convert it into a UNIX timestamp using strtotime, it must take in additional information to convert such an ambiguous relative time format into an absolute point in time. That information comes from date_default_timezone_set, or whatever is set equivalently in your php.ini.
Your problem almost certainly just boils down to the timezone PHP assumes when doing strtotime not being the same timezone as what your MySQL datetime string is actually for. E.g., if your MySQL datetime expresses the time for UTC, but strtotime assumes Bucharest as the timezone to use, you'll see a difference of a few hours in the resulting absolute point in time.
Simply set/use the correct timezone in your PHP code; think about/be aware/decide on what timezone your MySQL dates are actually stored in.
Also see Does PHP time() return a GMT/UTC Timestamp?
The value returned by time() (a timestamp) is the number of seconds since Jan 1, 1970, 00:00:00 UTC. It is an absolute value.
The value you retrieve from the database (2016-03-24 10:17:01) is a relative value. It can represent different timestamps, depending on what time zone you use.
How to use the DateTime and DateTimeZone classes:
// Timestamp generated from PHP code
// Current time
$date1 = new DateTime(); // it uses the default timezone set in php.ini
// or by a previous call to date_default_timezone_set()
// be more specific
$date2 = new DateTime('now', new DateTimeZone('US/Eastern'));
// $date1 and $date2 represent the same moment in time ("now")
echo(($date1 == $date2) ? 'Yes' : 'No'); // It displays "Yes"
// Display them as timestamps
echo($date1->format('U')); // 1458816551
echo($date2->format('U')); // also 1458816551
// Display $date1 as human-readable format:
echo($date1->format('Y-m-d H:i:s e'));
// It displays: 2016-03-24 12:49:11 Europe/Bucharest
// Change $date1 to use the same timezone as $date2
$date1->setTimezone(new DateTimeZone('US/Eastern'));
echo($date1->format('Y-m-d H:i:s e'));
// Now it displays: 2016-03-24 06:49:11 US/Eastern
// It provides easy ways to generate another date:
$date3 = clone $date1; // create a duplicate
$date3->add(new DateInterval('P2D')); // modify the duplicate
// $date3 is 2 days in the future
echo($date3->format('Y-m-d H:i:s e'));
// It displays: 2016-03-26 06:49:11 US/Eastern
// Get the difference between $date3 and $date1
$diff = $date3->diff($date1)
// you get the difference in date components (days, hours, minutes etc).
print_r($diff);
A date-time value you extract from the database is incomplete. It lacks the timezone. If you stored the value in the database in the past then you should know what timezone it uses. If you get the datetime from the database using SELECT NOW() then the timezone is the default timezone used by the server. It is stored in the system_time_zone server variable and can be queried with SELECT ##system_time_zone
The query:
SELECT NOW() AS now, ##system_time_zone AS tz
returns the local date and time and the timezone used by the MySQL server.
You can use them to create a DateTime object to work with, as in the example code provided above.
As a general rule, always use a single time for the values you store as datetime in the database. I suggest using UTC because everything is relative to it and it doesn't observe DST. Or you can use columns of type TIMESTAMP instead (absolute timestamp do not care about timezones and DST) but they are more difficult to handle.
I am working on a project and I am having an issue formatting an epoch time to a human readable time.
I have the following epoch time 1428512160 and when I put this through epochconverter.com I get the human time of 08/04/2015 17:56:00 GMT+1:00 DST as expected.
I then use the following code in order to perform the conversion from the epoch time to a human date time.
$dt = new DateTime($supportDetails["Reported"]);
$reportedTimeString = $dt->format('d-m-Y H:i:s');
$supportDetails[Reported] is the epoch time (I've printed it so I know it's correct).
The result I get back however is 08-04-2160 14:28:51.
You need to add an # for the timestamp in the DateTime class, like this:
$dt = new DateTime("#" . $supportDetails["Reported"]);
//^ See here
You can also see this in the manual. And a quote from there:
Unix Timestamp "#" "-"? [0-9]+ "#1215282385"
Also note that the current timezone is getting ignored, which you can also see in the manual:
Note:
The $timezone parameter and the current timezone are ignored when the $time parameter either is a UNIX timestamp (e.g. #946684800) or specifies a timezone (e.g. 2010-01-28T15:00:00+02:00).
Printing date and time is correct.
Its based on what GMT you have set in your PHP.
If you printing with GMT you will get required result.
Try the following code:
$reportedTimeString = date("d-m-Y H:i:s", $supportDetails["Reported"]);
Or the following:
$date = new DateTime();
$date->setTimestamp($supportDetails["Reported"]);
$reportedTimeString = $date->format("d-m-Y H:i:s");
The problem I see is with your formatting.
If you look at PHP's date function you can see that you just need to write each portion of the desired date & time into a string.
The following formatting gives the same output you were looking for:
$dt = new DateTime($supportDetails["Reported"]);
$reportedTimeString = $dt->format('d/m/Y H:i:s \G\M\TP T');
i am changing server time into another time zone using belowcode
$datetime = new DateTime(2014-02-27 03:03:00);
$la_time = new DateTimeZone('America/New_York');
$datetime->setTimezone($la_time);
$dateformat="Y-m-d h:i A";
return $datetime->format($dateformat);
its working fine except AM/PM...
correct result is: 02-26-14 10:03 AM but i am getting result as 02-26-14 10:03 PM.
can you please tell me where the problem
The result will always be based on the original timezone setting. If you want to convert to a different timezone, you must initialize the DateTime object after setting the timezone.
Here's a function to make the job easier:
function convertTimezone($date,$from_tz,$to_tz,$format='Y-m-d h:i A') {
$date = new DateTime($date, new DateTimeZone($from_tz));
$date->setTimezone(new DateTimeZone($to_tz));
return $date->format($format);
}
The function could be improved by checking if the supplied timezones are valid.
Example Usage:
echo convertTimezone('2014-02-27 03:03:00','Pacific/Nauru','Pacific/Chatham');
Output:
2014-02-27 04:48 AM
Demo
Set the timezone when you initialize the DateTime:
$datetime = new DateTime("2014-02-27 03:03:00", new DateTimeZone('America/New_York'));
$dateformat="Y-m-d h:i A";
return $datetime->format($dateformat);
When you set a DateTime, it uses the timezone then in effect. If you change the timezone later, it will change the representation of the time, but the time will be based on the original timezone setting.
EDIT: I didn't read the question carefully enough; you should set the time zone when you initialize the DateTime object, as in the manual.
How can I convert the time zone of a date string in php without changing the default time zone. I want to convert it locally to display only. The php time zone settting should not be modified.
EDIT:
My source time is a UTC string, I want to convert it to a different format, retaining the time zone as UTC, but php is converting it to local timezone.
The code I used was:
date('Y-m-d H:i::s',strtotime($time_str));
How do I retain timezone?
$src_tz = new DateTimeZone('America/Chicago');
$dest_tz = new DateTimeZone('America/New_York');
$dt = new DateTime("2000-01-01 12:00:00", $src_tz);
$dt->setTimeZone($dest_tz);
echo $dt->format('Y-m-d H:i:s');
Note that if the source time is UTC, you can change the one line to this:
$dt = new DateTime("2000-01-01 12:00:00 UTC");
Edit: Looks like you want to go to UTC. In that case, just use "UTC" as the parameter to the $dest_tz constructor, and use the original block of code. (And of course, you can omit the $src_tz parameter if it is the same as the default time zone.)
I am using Wanp as a testing server. Here is my code:
$dt = time();
$mysql_datetime = strftime("%Y-%m-%d %H:%M:%S %p %z" , $dt);
echo $mysql_datetime;
Here is the output:
2011-04-17 01:36:55 PM Eastern Standard Time
My problem is that, all the information is correct except or the hour, which is 4 hours ahead. The hour (01 PM) is suppose to be (09 AM). I have checked my date and time on my computer, and the time zone is correct. What would cause this to happen, please help.
Chances are this is due to the timezone being set incorrectly. (Although it's odd that the %z is correct, which I'm presuming it is.)
Have you tried calling date_default_timezone_set with the appropriate timezone value?
You have to set your timezone correctly first before anything else.
Use date_default_timezone_set. Here is list of supported timezones.
Could you try using the DateTime class (assuming you have a reasonably recent php)?
Something like:
$dt = new DateTime();
echo $dt->format('Y-m-d H:i:s A e');
Alternatively if it still gets the timezone wrong, you could try to specify it:
$dt = new DateTime(null, new DateTimeZone('EST'));
echo $dt->format('Y-m-d H:i:s A e');
Anyway for more debugging information I'd recommend you look at ini_get('date.timezone') which, if incorrect, should be configured properly in your php.ini file.