Nabin  Nembang
Nabin Nembang

Reputation: 753

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?

Upvotes: 0

Views: 913

Answers (3)

RobG
RobG

Reputation: 147363

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

Upvotes: 2

user1433439
user1433439

Reputation:

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.

Upvotes: 0

Yogus
Yogus

Reputation: 2272

Use

new Date(Date.NPT(year, month, day, hour, minute, second))

Upvotes: 0

Related Questions