0

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?

N Nem
  • 743
  • 8
  • 14
  • Javascript will always show your system date. if you need server time then you need to get the date or time from the server. – Harry Bomrah May 27 '13 at 04:35
  • http://stackoverflow.com/questions/439630/how-do-you-create-a-javascript-date-object-with-a-set-timezone-without-using-a-s – akonsu May 27 '13 at 04:35
  • @HarryBomrah—javascript Dates use a UTC time value that, by default, is based on a combination of the system settings for the timezone offset and system's current time. – RobG May 27 '13 at 05:51

3 Answers3

2

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
RobG
  • 142,382
  • 31
  • 172
  • 209
0

Use

new Date(Date.NPT(year, month, day, hour, minute, second))
Yogus
  • 2,307
  • 5
  • 20
  • 38
0

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.