javascript function new Date() not working - php

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.

Related

How to set php timezone by offset value in hh:mm, minuts or seconds?

My online application gets users timezone offset in + or - value in minutes. I want to set this value in server.
MySQL / MariaDB accepts timezone values and works perfectly
SET time_zone = "+0:15";
But php only accepts timezone string like this
date_default_timezone_set("Asia/Karachi"); // Works Perfectly
And does not set time in offset value
date_default_timezone_set("+0:15"); // Error
Is there any way to set php time with offset value?
After reading the documentation for the date_default_timezone_set() php function, this seems to be a common issue.
I'm sure there may be alternatives if you choose to use other date functions in php, however, to be able to set the timezone by an offset, you would require a helper function to do this.
I've copied and modified a helper function posted on the php doc page here
function setTimezoneByOffset($offset)
{
$testTimestamp = time();
date_default_timezone_set('UTC');
$testLocaltime = localtime($testTimestamp,true);
$testHour = $testLocaltime['tm_hour'];
$abbrarray = timezone_abbreviations_list();
foreach ($abbrarray as $abbr)
{
//$abbr."<br>";
foreach ($abbr as $city)
{
date_default_timezone_set($city['timezone_id']);
$testLocaltime = localtime($testTimestamp,true);
$hour = $testLocaltime['tm_hour'];
$testOffset = $hour - $testHour;
if($testOffset == $offset)
{
return $city['timezone_id'];
}
}
}
return false;
}
Where the parameter $offset is a string representation of the offset (ie. '+0:15'), which returns the timezone id of the timezone which matches that of your input.
My online application gets users timezone offset in + or - value in minutes.
This is problematic, because a time zone offset is not the same thing as a time zone. Consider that one cannot take the current offset and assume it is the correct offset to apply for any given date and time. Many time zones use more than one offset depending on time of year, and many time zones have had changes to their standard time offsets at different points in history. For more on this, see "Time Zone != Offset" in the timezone tag wiki.
As an example, you might be using a JavaScript function like new Date().getTimezoneOffset(). However, this returns the offset for the Date object returned by new Date() - which is the current date. For me, in the US Pacific time zone, it will return 480 (UTC-8) when run in the winter during standard time, but 420 (UTC-7) when run in the summer during daylight saving time.
Instead, have your front-end call Intl.DateTimeFormat().resolvedOptions().timeZone in JavaScript to return the time zone identifier, which for me returns "America/Los_Angeles". You can pass that to your back-end and use it with PHP.
As a side note, there are no time zones in the world that use or have ever used UTC+0:15. The closest to that would have been UTC+0:20 used in the Netherlands from 1 May 1909 to 16 May 1940. This is already captured in the history of "Europe/Amsterdam".

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

Comparing Two Dates in PHP

I have problem in comparing two dates. User will choose date from Datepicker with format ('Y-m-d'). If input is not equal to the current date then error message will showed up else output will be displayed.
I have this code:
$today = date("Y-m-d");
$date = $_REQUEST['selected_date']; // date selected
$first = strtotime($today);
$second = strtotime($date);
if ($first != $second){
//error message
}else{
//some code
}
This works fine in local but when i try to upload it, its not working anymore. Instead, the previous date can be accepted not the current date.
Probably the timezone is set differently on the server than from your local machine.
Try printing out the values of $first and $second.
You can (and should) set the timezone used by PHP with date_default_timezone_set() if you're using any of the old-style PHP date functions (date, strtotime etc).
Though I recommend using the DateTime & DateTimeZone classes with new code, they're nicer to work with, especially if you're doing anything involving multiple timezones.
Is there any possibility that the server is in a different time zone than where the request is coming from? I'd think this could lead to a mismatch.
Hopefully I understand your situation correctly. Attacking this directly will fail a lot of times because the server time zone (which you get through date()) will be different from the client time zone. To avoid this problem you need to send the client time to your server via javascript. jQuery example may look like this:
var date = new Date();
$.post("index.php", { today: (today.getMonth() + 1) + "/" + today.getDate() + "/" + today.getFullYear()}, function(data) {
alert(data); //server response here
});
on the server you get your client's today date as a string via $_POST['today']. Then you can decide what to do with it and output it to your client.
Alternatively, the problem you are describing can be solved just by JavaScript without sending it to your server unless you want to do something with it on your server

Convert all dates in PHP to local time

The server my PHP script is running on is set to UTC. I can't seem to figure out a way to set all dates to the browser's timezone. All dates displayed are formatted using PHP's date() function.
I know that via JavaScript's getTimezoneOffset() function, I can get the browser's current UTC offset (-4, in my case). How can I tell PHP to use this offset? I can use date_default_timezone_set(), but how do I convert an offset, say -4, to a time zone string, say America/New_York?
Note: The server is running PHP 5.1.6 (with no DateTime class) and I am using CodeIgniter.
As per the comment above- you could use a cookie...:
Javascript:
var today = new Date();
function SetCookie(cookieName,cookieValue,nDays) {
var expire = new Date();
if (nDays==null || nDays==0) nDays=1;
expire.setTime(today.getTime() + 3600000*24*nDays);
document.cookie = cookieName+"="+escape(cookieValue)
+ ";expires="+expire.toGMTString();
}
SetCookie("datecookie", today, 30);
window.location.href=window.location.href
PHP:
echo date("m d Y", strtotime($_COOKIE['datecookie']));
Because Javascript is client based and PHP is server based, they will not communicate. To tell the server the browser time, you will need to send information from the client, perhaps via Ajax, posting the browser time. The target PHP script should then handle/output this as appropriate. One other (obtuse) option is to attempt to geolocate the user based on IP, then guesstimate the correct time for that location- however this is inefficient for this purpose.
"I know I can use date_default_timezone_set(), but how do I convert an offset, say -4, to a time zone string, say America/New_York?"
Simply look at the comments associated with the documentation for that function. Comment #99006 does the work for you. You just need to get the timezone offset from the user.

How do I get the local system time in 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>

Categories