How do I get the local system time in PHP? - php

I'm writing a PHP system and I need to get the system time. Not the GMT time or the time specific to a timezone, but the same system time that is used by the CRON system. I have a CRON job that runs every day at midnight and I want to show on a webpage how long will it take before it runs again.
For example:
Right now it is 6pm on my system clock. I run the code:
$timeLeftUntilMidnight = date("H:i", strtotime("tomorrow") - strtotime("now"));
The result, however, is "3:00" instead of "6:00". If I run
date("H:i", strtotime("tomorrow"));
It returns 0:00, which is correct. But if I run
date("H:i", strtotime("now"));
It returns 21:00, even though the correct should be 18:00.
Thanks.

There are many answers, however there is not even one correct at the time of writing.
PHP time() function doesn't return the system time, like most folks believe, but it return the PHP localtime, normally set with date.timezone in php.ini, or set with date_default_timezone_set() within a script.
For instance in one of my servers, PHP time was set to Europe/Romeand system time to UTC. I had a difference of one hour between system time and PHP time.
I'm going to give you a solution that works for Linux, I don't know for Windows. In Linux the system timezone is set in /etc/timezone. Now, this is normally outside my allowed open_basedir setting, but you can add :/etc/timezone to your list to be able to read the file.
Then, on top of the scripts, that want to get the system time, you can call a library function that sets the script timezone to the system timezone. I suppose that this function is part of a class, so I use static:
static function setSystemTz() {
$systemTz = trim(file_get_contents("/etc/timezone"));
if ($systemTz == 'Etc/UTC') $systemTz = 'UTC';
date_default_timezone_set($systemTz);
}
To make the matter worse in PHP 5.3.3 'Etc/UTC' is not recognized, while 'UTC' is, so I had to add an if to fix that.
Now you can happily call time() and it will really give you the system time. I've tested it, because I needed it for myself, that's why I found this question now.

php's time will return the system time. you can format it with date
if you just want to display the time in the local time of the visitor maybe you're better off using a little javascript

This is the easiest and most foolproof way to do it:
$sys_timestamp = strtotime(exec("date"));
Let's not try to spoof it with php, let's just get the real sys time ;)
(Will work on any unix based system)

time()
will give you the current system timestamp.
Manual
Returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).

You can get the date/time of the server on which PHP is running using the time() function -- it'll return a timestamp, that corresponds to the current datetime.
It's the system time, on that server -- the same as used by cron.

If you want the GMT time you may want to use gmtstrftime(), which will give you the system time but as in GMT. There's more info at http://us2.php.net/gmstrftime.

If you are after a formatted date:
date ('d/m/y h:i:s');
will do the trick, there is no need to pass time() into date as it will default to the current system time if no second parameter is supplied.
for more formatting options see here: http://php.net/manual/en/function.date.php
Otherwise you can just use
time()
To get you the current unix timestamp as others have mentioned.

For getting the current time of your system you need to set the correct date.timezone in your php.ini file. For example if you are from India then you would write:
date.timezone = Asia/Calcutta
For Germany, it would be:
date.timezone = Europe/Berlin
After doing this, date("Y-m-d H:i:s") will give your current time. For getting your timezone see the list of timezones supported by PHP.

try this one:
$time=date("h:i:s A", strtotime("now"-14));
echo $time;
You can adjust the time by changing the number 14 above.

You can current local time via below Javascript and set it in any PHP variable than.
<script>
// For 24 hours
var ct = new Date();
var hr = ct.getHours();
var mt = ct.getMinutes();
if (mt < 10) {
mt = "0" + mt;
}
document.write("<b>" + hr + ":" + mt + " " + "</b>");
// For 12 hours (AM / PM)
var ct = new Date();
var hr = ct.getHours();
var mt = ct.getMinutes();
var ampm = "AM";
if (hr >= 12) {
ampm = "PM";
hr = hr - 12;
}
if (hr == 0) {
hr = 12;
}
if (mt < 10) {
mt = "0" + mt;
}
document.write("<b>" + hr + ":" + mt + " " + ampm + "</b>");
</script>

Related

Adding 2 different timestamp and dealing with PHP Datetime class

I'm building an application that shows specific times on a given day. This application is meant to serve ppl worldwide.
I do all the calculation with a TZ in an hour format (-4 / 2 / 9.5 / -1 ETC). (don't worry. the hour tz is after DST calculations)
Now, I would like to show the user his local time. due to dev reasons, i can use only the hour tz for this calculation.
after a lot of tries, i maneged to write a piece of code that seems to work. (tested it for few timezones, negetive and positive)
I am wondering if my code is ok? could i do it in a more efficent way? do this code support infinite date range?
here is the code:
static function current_local_time_zmanim($tz)
/*
* This function will get the number of hours off set (the time zone that Full_Zmanim_calculation() is using to make the calcukation) and will return the current local time and date.
*/ {
$tz= ($tz * 3600);// calculatoin: (hour offset(tz. can be -4 or 4) * 3600). eg: (-4*3600) or (3*3600)// converting the hour tz to TIMESTAMP
$date_utc = new DateTime(null, new DateTimeZone("UTC")); // current time in UTC.
$utctime= $date_utc->getTimestamp(); // current time in UTC TIMESTAMP
$date_utc->setTimestamp($utctime + ($tz));// keep in mind that tz can be either positive or negetive
$localtime= $date_utc->format('H:i');
echo "<br> local time: $localtime <br> ";
return $localtime;
}
What do you think?
Thanks!

How to get the UK timezone in PHP and detect midnight?

I am learning some PHP. I have a script which checks to see if a JSON file exists. If it does not exist; it will populate it with some YQL and some data. If it exists, it will not do anything as it is better for cache and speed.
In my code; I have this line (currently only doing every 3 hours (10800)):
if ( !file_exists($cache) || filemtime($cache) < ( time() - 10800 ) ) {
What I want do is, despite the server time, I want to use the UK GMT timezone and check to see if it is 00.01 past midnight, if it is, that is when I want to update the script. Every day at 00.01 midnight in the UK. Now I have heard PHP supports timezone but I only want it on this script?
This is what I have tried.
// TIMEZONE
date_default_timezone_set("Europe/London");
$date = $date();
$timestr = $time();
$timestamp = strtotime('today midnight');
// VARS
$cache = '../media/js/data.json';
// VALIDATION
// -- The cache is new
if ( !file_exists($cache) || filemtime($cache) < ( time() - timestamp ) ) {
another approach would be as mentioned would be cron jobs. you mentioned you want uk time zone , in that case please set your php.ini time zone to UK. this is how you do it
//add this line or replace within your php.ini file
; Defines the default timezone used by the date functions
date.timezone = "Europe/London"
and then set the cron job.
I'm using some stuff like that
$timezone = "Your timezone";
$tmpTZ = date_default_timezone_get();
date_default_timezone_set($timezone);
// some code to generate the date
date_default_timezone_set($tmpTZ);
Putting that in a small function an your ready to go.
The easiest solution will be usage of Cron, just calculate the difference between 2 timezones, and add task on the calculated time
http://www.thegeekstuff.com/2009/06/15-practical-crontab-examples/

javascript function new Date() not working

My problem is as follows:
I want to display nepalese standard time in my website,so i set default timezone of my
website to 'Asia/kathmandu' using command: php_value date.timezone 'Asia/kathmandu' in htaccess file.
when i display time using any php functions like strftime() or date() ,it shows the nepalese standard time,
But when i use javascript function new Date(<?php echo time()*1000; ?>),it displays
the time of my personal pc i am using to view my website.
How can i display correct time using javascript date functions? Can anybody help me out?
Your issue is because javascript (actually ECMAScript) date objects are based on a UTC time value. When you do:
new Date(<?php echo time()*1000; ?>)
you are passing a UTC millisecond time value to the Date constructor, which then creates a date object. When you use the usual Date methods to format a string, or use Date.prototpye.toString or Date.prototype.toLocaleString, you will get a string based on the client's locale. Note that all these strings are implementation dependent and vary widely for the locale version.
If you want the timezone of the server, then use the server to set it. Or you can send a time zone offset in minutes to be applied to the local time to get back to Nepalese Standard Time (UTC + 5:45). Note that in ECMAScript, the time zone offset is minutes to be added to the local time to get UTC, whereas it is more normal to define the offset in minutes to be added to UTC to get the local time.
So to get NST:
function toNST(timeValue) {
function z(n) {return (n<10? '0' : '') + n}
var d = new Date();
var nstOffset = 5 * 60 + 45;
d.setMinutes(d.getMinutes() + d.getTimezoneOffset() + nstOffset);
return z(d.getHours()) + ':' + z(d.getMinutes()) + ':' + z(d.getSeconds());
}
alert(toNST(+(new Date()))); // about 11:07:17 at the moment
Use
new Date(Date.NPT(year, month, day, hour, minute, second))
Call the time via ajax from your server. That has the advantage of a better code maintanance. If you change the time again (e.g. if you want to use the code for another location) you have only to change the time in .haccess.

How to show a Unix-time in a local time format

I have a php variable say $expTime (which has a unixtime say-1359683953) . I want to display this variable on the client side(in a proper time format according to his local time) . I am so confused between the UTC ,GMT , DST all that things. Can anyone suggest a solution for this using php or javascript please.
when I am using echo date('h:i M d/y',$expTime) it is showing me a wrong time.
How I am saving the time to database:
var exp_day= parseInt($("#exp_day").val());
var exp_hrs= parseInt($("#exp_hrs").val());
var exp_min= parseInt($("#exp_min").val());
var exp_time = (exp_day*24*60*60) + (exp_hrs*60*60) + (exp_min*60) ;
then I posted the exp_time using ajax to a php file -
$expTime = time() + $_POST["exp_time"];
What I am retrieving from the database is $expTime . This $expTime I want to display it on the all the clients system according to there local time zone (also by making sure the day light saving)
Use DateTime with timezones:
$datetime = new DateTime('#1359683953');
echo $datetime->format('h:i M d/y') . "<br>";
$datetime->setTimezone(new DateTimeZone('America/Los_Angeles'));
echo $datetime->format('h:i M d/y');
See it in action
UNIX time values are usually UTC seconds since epoch. Javascript time values are UTC milliseconds since the same epoch. The ECMA-262 Date.prototype.toString method automatically generates a string representing the local time and takes account of daylight saving if it applies.
You can also use Date methods to create your own formatted string, they also return local time and date values. There are also UTC methods if you want to work in UTC.
To do this on the client, just provide a UTC time value from the server and then all you need in javascript is:
var timeValue = 1359683953; // assume seconds
var date = new Date(timeValue * 1000); // convert time value to milliseconds
alert(date); // Fri 01 Feb 2013 11:59:13 GMT+1000

How to display local time with PHP

Our server is set to GMT time so the hour does not keep jumping around in spring and autumn. However, during summer time, it is annoying that all the times are displayed an hour out.
How do I get and display the time, taking into account the local timezone in PHP (especially when the server thinks the local timezone is GMT).
or, How do I know if an area is using "summer time" at the moment?
or, How do I display a GMT time stamp or a different timezone?
Actually, I think I may have found the answer I need...
date_default_timezone_set()
// Sets the default timezone used by all date/time functions in a script
The PHP manual entry is here:- http://us2.php.net/manual/en/function.date-default-timezone-set.php
You could add this line in PHP:
putenv("TZ=US/Eastern");
And every subsequent call to time()/date() will give you the time in your time zone.
List of time zones
This code will display the current time in the Eastern time zone (US):
putenv("TZ=US/Eastern");
date("h:i:s")
You can use the date function to offset GMT
Easiest way to display local time is to use JavaScript:
<?php
// Get unix time from database
$seconds = .....;
?>
<html>
<head>
<script type="text/javascript">
function showLocalTime()
{
var seconds = <?=$seconds;?>;
var date = new Date(seconds*1000);
var hours = date.getHours();
var minutes = "0" + date.getMinutes();
var seconds = "0" + date.getSeconds();
var formattedTime = hours + ':' + minutes.substr(minutes.length-2) + ':' + seconds.substr(seconds.length-2);
document.getElementById("local_time").innerHTML = "Local Time: " + formattedTime;
}
</script>
</head>
<body onload="showLocalTime()">
<h2 id="local_time"> Local Time: </h2>
</body>
</html>
get the date/time and first check to see if the month (split on dashes if its a DATETIME field) is a 'summer month', or a month that will cause the time to be an hour out.
If so, convert it to a unix timestamp. Then, add (or minus, whichever way it is out) 60 * 60 (60 mins) to the timestamp and convert into a human readable format.
Problem solved!

Categories