Set GMT+8 PHP Time [duplicate] - php

This question already has answers here:
Dealing with timezones in PHP
(4 answers)
Closed 9 years ago.
I have some php scripts on a hosting, but hosting time is different from my local time (GMT+8)
How set the right time() script to be GMT+8 ?
When i use:
<?
echo time(); //it show me the hosting time;
?>

time() will always return the number of seconds since the epoch. The code below will print the same twice.
date_default_timezone_set('Europe/London');
echo time();
date_default_timezone_set('America/Cuiaba');
echo time();
The concept of Unix Timestamp does not carry time zone information by design. A given timestamp is always the same regardless of time zone. (The number of seconds since 1970-01-01 00:00:00 UTC) When you want to express a timestamp with time zone taken into account, you will adjust the resulting date with the current time zone's offset.
So when using the 'c' format option to PHP's date (which does reflect time zone information) you will see different representation of the same timestamp
date_default_timezone_set('Europe/London');
echo time();
echo date('c')
date_default_timezone_set('America/Cuiaba');
echo time();
echo date('c');
Will output:
1384259474
2013-11-12T12:31:14+00:00
1384259474
2013-11-12T09:31:14-03:00

Your assumption is not correct:
int time ( void )
Returns the current time measured in the number of seconds since the
Unix Epoch (January 1 1970 00:00:00 GMT).
The Unix Epoch is a fixed moment in time. If you really get an invalid timestamp, your hosting provider has not cared to set the server's clock.
If you want to do decent time zone aware date handling I suggest you learn about the DateTime class and friends and:
Use named time zones (Europe/Madrid) rather than UTC offsets (+01:00) since they take DST into account.
Set your app's time zone as default so you don't need to specify it every time:
date_default_timezone_set("Europe/Helsinki");
Never ever do date math yourself (e.g., don't add 86400 seconds manually to increase a day).

You must set the local time in php
function date_default_timezone_set
List of Supported Timezones
Example:
date_default_timezone_set("America/Fortaleza");
echo time(); // Local Time in America/Fortaleza

Add 28800 (8 hrs converted to seconds) to the output of time()
<?php echo (time()+28800); ?>
I am not sure but, time() returns timestamp which is equivalent to GMT thus, adding timestamp of 8 hours will give you GMT+8. Similarly, you can even subtract the time also

You can use date_default_timezone_set() function, For example
date_default_timezone_set('Asia/Dhaka');

Related

Convert date format 1542575966120 18/11/2018 [duplicate]

This question already has answers here:
Convert one date format into another in PHP
(17 answers)
Closed 4 years ago.
I have a DB that shows when the user made the last login but then it shows 1542575966120. I wanted it to show so 18/11/2018 19:00
I tried using this in php
$intDate = "20". $ infologado ["lastlogin"];
$newDate = date ("d-m-Y", strtotime ($ intDate));
but I could not.
sorry for English
So as #Taha Paksu had mentioned, these numbers are a timestamp (seconds since 1 January 1970). Try this code:
$intDate = 1542575966120;
$newDate = date('d/m/Y H:i', $intDate/1000);
It is in miliseconds, date function accepts seconds, thus the division by 1000. Also no need to put it into strtotime, because this function is meant to convert string dates to... said numeric timestamps.
In your case, you can put $intDate = $infologado['lastlogin']; instead of first line to get the result dynamically from the database.
First of all, you need to learn what a timestamp is. The timestamp is a number which shows the seconds passed (or milliseconds, some include the milliseconds too) since epoch (01/01/1970). A general definition can be found here:
The Unix epoch (or Unix time or POSIX time or Unix timestamp) is the number of seconds that have elapsed since January 1, 1970 (midnight UTC/GMT), not counting leap seconds (in ISO 8601: 1970-01-01T00:00:00Z). Literally speaking the epoch is Unix time 0 (midnight 1/1/1970), but 'epoch' is often used as a synonym for 'Unix time'. Many Unix systems store epoch dates as a signed 32-bit integer, which might cause problems on January 19, 2038 (known as the Year 2038 problem or Y2038).
The converter on this page converts timestamps in seconds, milliseconds and microseconds to readable dates.
Taken from: https://www.epochconverter.com/ a tool which you can convert your dates to/from timestamps or vice versa.
Then to answer your question, the system saved the dates as a timestamp to the database to (probably) bypass the formatting errors on each different system that uses it.
Nevermind, TL;DR:
The number shows Sunday, 18 November 2018 21:19:26.120 when you give it to the timestamp converter I mentioned above. With PHP, you can use:
$unixTimestamp = 1542575966120;
$dt = DateTime::createFromFormat("U.u", $unixTimestamp / 1000);
var_dump($dt);
to convert to PHP DateTime class, then you can use it in your application.

php time difference between current time and database time [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have database. I save my value on 1480079589 time.
I want to measure time between current time and my database time which I saved.
I don't have any idea because of I dın't understand time logic. 1480079589 is what time ?
To calculate time difference
SELECT timestamp AS 'thisisit'
FROM table
WHERE TIMESTAMPDIFF(MINUTE, timestamp, NOW()) <= 15;
This is a timestamp.
Use PHP's date() function.
Example:
echo date('m/d/Y', 1480079589);
Simply put, the Unix timestamp is a way to track time as a running
total of seconds. This count starts at the Unix Epoch on January 1st,
1970 at UTC. Therefore, the Unix timestamp is merely the number of
seconds between a particular date and the Unix Epoch. It should also
be pointed out that this point in time technically does not change no
matter where you are located on the globe. This is very useful to
computer systems for tracking and sorting dated information in dynamic
and distributed applications both online and client side. The reason
why Unix timestamps are used by many webmasters is because they can
represent all time zones at once.
Please refer to this for more info:
http://php.net/manual/en/datetime.settimestamp.php
Refer to this question too:
What is a Unix timestamp and why use it?
1480079589 is timestamp, that is number of seconds from the time landmark (1970-01-01 00:00:00). That means 1480079589 seconds away from the landmark.
date('Y-m-d H:i:s', 1480079589);
that will print the date in a friendly way for you to see
That`s UNIX Time.
The unix time stamp is a way to track time as a running total of seconds.
This count starts at the Unix Epoch on January 1st, 1970 at UTC.
Therefore, the unix time stamp is merely the number of seconds between a particular date and the Unix Epoch.
It should also be pointed out (thanks to the comments from visitors to this site) that this point in time technically does not change no matter where you are located on the globe. This is very useful to computer systems for tracking and sorting dated information in dynamic and distributed applications both online and client side.
To get time difference try this:
<?php
$databaseTime = 1480079589; // Time from DataBase
print(time() - $databaseTime); // How much second
The time format is seconds since midnight 1/1/1970. Also known as Unix Time or timestamp.
You get this is php with the time() function. To measure time passed you could just compare two timestamps and get the seconds inbetween.
You convert a timestamp to a human readable format using
gmdate("M d Y H:i:s", $unixTimestamp);
date("M d Y H:i:s", $unixTimestamp);
I use
DATE_SUB(NOW(),INTERVAL 5 MINUTE)
in sql query. and my problem is solved.

PHP mktime and timezone

I'm working on some time related features and I opt to always use UTC times and store time stamps as integers for consistency.
However, I noticed that when I use mktime it seems that the currently set time zone has an influence of the return value of mktime. From the documentation I understand that mktime is supposed to return the number of seconds since epoch:
Returns the Unix timestamp corresponding to the arguments given. This
timestamp is a long integer containing the number of seconds between
the Unix Epoch (January 1 1970 00:00:00 GMT) and the time specified.
http://php.net/manual/en/function.mktime.php
However, it seems that mktime is including the time zone that is currently set. When using the following code:
date_default_timezone_set('UTC');
$time = mktime(0, 0, 0, 1, 1, 2016 );
echo "{$time}\n";
date_default_timezone_set('Australia/Sydney');
$time = mktime(0, 0, 0, 1, 1, 2016 );
echo "{$time}\n";
I would expect the two time vales to be same but apparently they are not:
1451606400
1451566800
Which seems to be exacly an 11 hour difference:
1451606400 - 1451566800 = 39600 / (60*60) = 11
What do I not understand correctly about mktime and/or why is the time zone taken into account when using mktime?
I can't tell you why it is the way it is (PHP has never made sense to me when it comes to date and time) but there is an alternative function gmmktime() which is
Identical to mktime() except the passed parameters represents a GMT date. gmmktime() internally uses mktime() so only times valid in derived local time can be used.
There is also a comment on the PHP documentation for this function which explains how mktime(), gmmktime() and time() work. Essentially, they assume that you always think in time zones even if a UNIX timestamp itself doesn't carry a timezone.
Resulting Unix timestamp are indeed encoded in a timezone agnostic way, but input arguments are interpreted relative to the timezone set for current process. And indeed, Sidneys 2016-01-01 00:00:00 (GMT+11) happened 11 hours before UTC 2016-01-01 00:00:00.
When some foreigner tells you a time, you have to know its time zone to correctly interpret it, and so does mktime().
If dates you want to pass to mktime() are UTC dates, then use gmmktime() which exists for that purpose.

If value of time() in PhP not influenced by timezone then why date function default to it?

According to http://www.php.net/manual/en/function.date.php
The optional timestamp parameter is an integer Unix timestamp that
defaults to the current local time if a timestamp is not given. In
other words, it defaults to the value of time().
However, in definition of time() there is no mention that it's time zone dependent. Which one is right?
time() returns the number of seconds since 00:00 1/1/1970 GMT.
The elapsed number of seconds since the UNIX epoch is the same no matter in which timezone you are.
No, the value returned by time() is timezone independent:
date_default_timezone_set("UTC");
echo "UTC:".time();
echo "<br>";
date_default_timezone_set("Europe/Helsinki");
echo "Europe/Helsinki:".time();
echo "<br>";
Both output the same value.
Regarding your edit, the return value of time() depends on what the current time on your machine is. The current time on your machine is typically set by specifying a time zone, as well as a date + time.
When we say the value returned by time() is timezone independent, we mean that at any given instant, the correct value for UTC time at all locations on earth is the same.
Suppose a person in Japan were to correctly set their system time (along with timezone), and another person in India were to do the same. At any given instant, if they were to invoke time() simultaneously, they would get the same value.
I think the documentation is just slightly vague, meaning "local" as in "of the machine it's running on". Or you could make it to mean that since date formats the timestamp according to the set timezone, the value returned by date will be the "local" time.
I.e., the "local" doesn't really mean anything here.
I think I know the issue.
time() it self is time zone independent.
However,
date() is time zone dependent. How the data is formatted depend on date_default_timezone_set
So, following Asad's answer
date_default_timezone_set("UTC");
echo "UTC:".date(...);
echo "<br>";
date_default_timezone_set("Europe/Helsinki");
echo "Europe/Helsinki:".date(...);
echo "<br>";
will produce different value. They both use time

PHP in Windows, how to obtain the current system time that ignores the timezone?

I have the next problem. I have several PHP systems running in different Windows machine. Those systems use intensivelly the current time.
Right now, i configured php.ini and assigned it to a specific timezone. Also Windows is configure to the same timezone and everything works as expected.
However, in my country, the State decided to change the daylight saving time. So, sometimes, the admin changes the windows timezone and left unchanged the php timezone, creating a discordance in the system. Other times, is windows who changes automatically the timezone.
Is there are any way, from PHP, to obtain the current system time that ignores the timezone?.
update:
function time_zone_fix($timeGiven = "H:i:s")
{
$shell = new COM("WScript.Shell") or die("Requires Windows Scripting Host");
$time_bias = -($shell->RegRead("HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\TimeZoneInformation\\ActiveTimeBias")) / 60;
$timestamp_bias = 60 * 60 * $time_bias;
return gmdate($timeGiven, strtotime($timestamp_bias . " seconds"));
}
gives the current date and time no matter what timezone/dsl is specified.
However, creating a new COM inteface is anything but efficient.
gmdate('Y-m-d H:i:s');
changing the format to whatever you need. It returns the "timezone-less date-and-time". The gm stands for Greenwich Mean, as in GMT (Greenwich Mean Time). GMT has been superseded by UTC (Universal Time, Coordinated), so the function should really be called utcdate()...
But the most portable representation of time is the Unix timestamp, i.e., the number of seconds elapsed since 1970-01-01 00:00:00 UTC, ignoring leap seconds:
time();
The value of time() is also the default value for the second parameter of gmdate().
BTW, a leap second is scheduled for 2012-06-30 23:59:60
Note: In case you are asking for a way to get the time at a certain timezone but without the daylight saving time correction, you can do this:
gmdate('Y-m-d H:i:s', time() + 3600 * $h);
where $h is the offset in hours from UTC (a negative number in America), or, in case the offset is not a full number of hours:
gmdate('Y-m-d H:i:s', time() + 60 * $m);
where $m is the offset in minutes from UTC (e.g., 330 for IST, India Standard Time). A Unix timestamp with an added timezone offset doesn't make any sense by itself, though!
Last but not least, don't forget to synchronize your systems by means of NTP, the Network Time Protocol.
PHP Manual List of Supported Timezones:
... Here you'll find the complete list of timezones supported by PHP, which are meant to be used with e.g. date_default_timezone_set(). ...
And then this one: UTC (from this sub-page)
PHP in Windows, how to obtain the current system time that ignores the timezone?
I have the next problem. I have several PHP systems running in different Windows machine. Those systems use intensivelly the current time.

Categories