PHP date() function ignores the timestamp parameter - php

The output of the following program can be seen here: http://codepad.org/egNGJBUL
<?php
/* Checking if time() is really timezone independent */
date_default_timezone_set('UTC');
echo time();
echo "\n";
date_default_timezone_set('Australia/Queensland');
echo time();
echo "\n";
/* Using date() function passing timestamp parameter */
date_default_timezone_set('UTC');
echo date('Y-m-d H:i:s',time());
echo "\n";
date_default_timezone_set('Australia/Queensland');
echo date('Y-m-d H:i:s',time());
echo "\n";
/* Using date() function without passing timestamp parameter */
date_default_timezone_set('UTC');
echo date('Y-m-d H:i:s');
echo "\n";
date_default_timezone_set('Australia/Queensland');
echo date('Y-m-d H:i:s');
echo "\n";
From line 1-2 of the output, we can see time() returns a value which is really timezone independent.
In line 3-4, it's strange that date() function ignores the timestamp parameter and still display the date time according to the timezone set.
Why is it like this?

Not really sure what you are expecting to see, but yes, looks very normal to me.
A timestamp is a integer counted from a certain point in time (usually the UNIX EPOCH). While the display of this value is timezone independent, it is no more or less so that say, the value of a properly formatted date, notated with a timezone, is timezone independent...
example, all of the following statements are both true (logically)
1297799809 == 1297799809
2011-02-15 19:56:49 (UTC) == 2011-02-16 05:56:49 (Austria/Queensland)
All time is 'timezone independant'. Timezones only affect the way we display a particular moment in time.

date() functions second parameter, if not specified, is time() value.
date() Returns a string formatted according to the given format string using the given integer timestamp or the current time if no timestamp is given. In other words, timestamp is optional and defaults to the value of time().
from date()'s manual
So actually nothing is being ingnored.

The date function returns the date of a timestamp calculated for the current timezone, as others have said, if no timestamp is passed to it, then the current time is used for the timestamp, so passing time() is the same as not passing anything at all.
However, doing something like $time = time();sleep 5;echo date($format,$time); will get you a date 5 seconds in the past.
It's meant to display the date formatted for current timezone so you can have a universal method of keeping time that's constant across computers/servers and be easily parsable, and yet be able to display the date in any timezone desired.
The UTC timezone is actually the time that the timestamp is calculated to, more precisely, the number of seconds since 00:00 Jan 1, 1970 UTC, then it adds or subtracts 3600 (60*60) seconds from/to the timestamp per hour offset from UTC time to get the time in the currently set timezone.

Related

Php date() function add extra day

I'm trying to echo out the current system date. But it outputs the date of tomorrow. I double check the System Date and tested changing the date. Still it adds 1 extra day when echoing out.
What could be the problem?
<?php
echo date("Y-m-d");
?>
If not specified, 2nd argument for date() defaults to current Unix timestamp - amount of seconds since 01.01.1970, 0:00 GMT.
You can use this to set your timezone, or manually convert the date to correct one: date($format, time() + $difference).

PHP: strtotime() and time() shows different timestamp

echo strtotime('2017-05-03 16:16:01');
echo "<br>";
echo time();
I ran this query at 2017-05-03 16:28:01 so output of time() should be higher and strtotime('2017-05-03 16:16:01'); should be lower but I am not getting the output.
above code prints
1493828161
1493809172 //
But I expected it to print if I run the query at 2017-05-03 16:02:01 same timestamp
1493809172
1493809172
But it prints with big difference.
time() return dynamic current timestamp which will change every moment.
Where as your passed date is static date, which will convert it into its timestamp() value and will show it.
Conclusion : time() is that which can not be stopped, it run as time pass by whereas timestamp with given date time, it will always show static value timestamp of given date time.
strtotime('2017-05-01 16:02:01')
Convert provided time into string to time
time ()
That convert to Returns the current time as a Unix timestamp

Why is the difference between timestamp unix time and time() incorrect?

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.

ISO date formats to wrong day

Short question but I can't get my finger on it. This piece of code:
$date = '2015-12-08T00:00:00+01:00';
echo date('D', strtotime($date));
returns Mon while
$date = '2015-12-08T00:00:00';
echo date('D', strtotime($date));
returns Tue. Why is that? The +01:00 is for the timezone, but that should not affect the day in my opinion.
First I've looked up that 08-12-2015 is in fact a Tuesday, so now we know the first one is incorrect.
PHP's date() is an Unix timestamp according to their own docs.
My belief is that adding the +1 as a timezone triggers the calculation to the +0 timezone (UTC) when asking for the day of the week and therefore returns 23:00 on monday as the current UTC time.
You can specify the timezone before executing the rest of the code: date_default_timezone_set('Europe/Amsterdam');
<?php
date_default_timezone_set('Europe/Amsterdam'); //this is an example of a +1 timezone, choose one from http://php.net/manual/en/timezones.php
$date = '2015-12-08T00:00:00+01:00';
echo date('D', strtotime($date) );
?>
strtotime will parse your date string using the supplied time zone or using the default timezone if unspecified. We can't see from the code you've posted what time zone your server is configured to, but once the date is parsed and converted to your time zone, the time may legitimately occur in the previous day, hence why you're seeing 'Mon'.
Either supply a time zone in the strtotime call via the now argument or set one globally with date_default_timezone_set.

PHP date() is wrong when using a UTC timestamp

$dayBasedOnUTC = date('l', $_GET['day']);
Why is it that when I echo the value of $dayBasedOnUTC the day returned is a Tuesday?
The UTC value of $_GET['day'] is: 1409393126144
If you put that number into any Unix Timestamp Converter you will see the date is Saturday.
It appears that 1409393126144 is a Javascript timestamp, which is counted in milliseconds. PHP expects its UNIX timestamps in seconds though. So 1409393126144 to PHP is a timestamp in the far future.
Divide by 1000 to get the correct value:
echo date('l', 1409393126144 / 1000);

Categories