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
Related
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.
So I have a site with a comments feature where the timestamp of the comment is stored in a MySQL database. From what I understand, the timestamp is converted to UTC when stored, then converted back to the default timezone when retrieved. In my case, my server is in the Central Daylight Time timezone (CDT).
I have a plan to get the timezone from each user via entry form. I just wanted to know how to convert the TIMESTAMP value into the user's timezone.
First, would I convert from UTC to local timezone? Or CDT to local timezone?
Secondly, how would I go about doing that in PHP? Would I just do:
$userTimezone = new DateTimeZone($userSubmittedTimezoneString);
$myDateTime = new DateTime($storedTimestamp, $userTimezone);
...or is that not correct?
Date/time/datetime values are stored in MySQL as you supply them. I.e. if you INSERT the string 2012-04-17 12:03:23 into a DATETIME column, that's the value that will be stored. It will be converted internally into a timestamp which may or may not be accurate (see below), but when you query for the value again, you'll get the same value back out; the roundtrip is transparent.
Problems may occur if you try to do time calculations inside SQL. I.e. any operation that requires SQL to take the timezone and/or the server time into account. For example, using NOW(). For any of those operations, the timezone and/or server time should be set correctly. See Time Zone Problems.
If that doesn't concern you and you only need to do calculations in PHP, you only need to make sure you know from which timezone to which timezone you want to convert. For that purpose it can be convenient to standardize all times to UTC, but it is not necessary, as timezone conversions from any timezone to any other timezone work just as well, as long as you're clear about which timezone you're converting from and to.
date_default_timezone_set('Asia/Tokyo'); // your reference timezone here
$date = date('Y-m-d H:i:s');
/* INSERT $date INTO database */;
$date = /* SELECT date FROM database */;
$usersTimezone = new DateTimeZone('America/Vancouver');
$l10nDate = new DateTime($date);
$l10nDate->setTimeZone($usersTimezone);
echo $l10nDate->format('Y-m-d H:i:s');
There is no reliable way to get the user's timezone. Timezone information is not sent in HTTP headers. The best that you could do is either:
Match the IP address againsta geographic database
-or-
Use Javascript to get the time set on the user's computer and either send that to the server (AJAX) or make the time string on the client.
$timezone = new DateTimeZone('America/Vancouver');
$date = new DateTime(date('m/d/Y h:i:s a', time()));
$date->setTimeZone($timezone);
echo $date->format('l F j Y g:i:s A')."\n";
Replace new DateTime(date('m/d/Y h:i:s a', time())); with new DateTime("UTC Time");
You can create a new DateTimeZone() object for each user input.
The way to do it is by using javascript. I think the best way to do it is by storing the users GMT into his cookies, and retrieving it on the PHP process form.
<script language="javascript">
function TimeZoneCookie()
{
var u_gmt = (-(new Date().getTimezoneOffset()))/60;
var o_date = new Date("December 31, 2025");
var v_cookie_date = o_date.toGMTString();
var str_cookie = "utimezone="+u_gmt;
str_cookie += ";expires=" + v_cookie_date;
document.cookie=str_cookie;
}
//---------------------
TimeZoneCookie();
</script>
u_gmt explained:
Date().getTimezoneOffset() returns the offset to GMT-0 in minutes
Since getTimezoneOffset() will return the offset to GMT-0 and not from GMT-0 we'll need to turn it around. How? simple, just by knowing that -*-=+ & -*+=-. If you know basic math, you already know this principle.
As I said in step 1 getTimezoneOffset() will return the offset in minutes, so we just divide it by 60, so we can get the gmt offset format.
Result: (-(new Date().getTimezoneOffset()))/60
Now retrieve the cookie in PHP:
<?php
$user_timezone = $_COOKIE['utimezone'];
?>
Hello i need to get this date value from php 1328569380 and convert it to javascript date.
By the way how is this date "1328569380" type of form called ?
The numeric date time your are referring to is called a timestamp. It is the number of seconds elapsed since january 1st of 1970 if i'm not wrong.
To send a date to javascript, just print it out using the timestamp x 1000 since it also accepts millisecond initialization format:
mydate = new Date(<?php echo $mytimestamp*1000; ?>);
Good luck
This is a Unix epoch timestamp. See the following thread for the how-to:
Convert a Unix timestamp to time in JavaScript
Your value is the number of seconds that has passed since 1970-01-01 00:00:00, called the Unix epoch.
JavaScript counts the number of milliseconds instead, thus you have to multiply your timestamp with 1000 prior to using it to create a JavaScript date-object.
var phptimestamp = 1328569380;
var date = new Date(phptimestamp * 1000);
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>
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!