[javascript] Get time of specific timezone

I am using a JavaScript Date class & trying to get the current date using getDate() method. But obviously it is loading system date & time. I am running the code from India but I want to get the date & time of UK using the same method. How can I do that ?

This question is related to javascript date time timezone

The answer is


If it's really important that you have the correct date and time; it's best to have a service on your server (which you of course have running in UTC) that returns the time. You can then create a new Date on the client and compare the values and if necessary adjust all dates with the offset from the server time.

Why do this? I've had bug reports that was hard to reproduce because I could not find the error messages in the server log, until I noticed that the bug report was mailed two days after I'd received it. You can probably trust the browser to correctly handle time-zone conversion when being sent a UTC timestamp, but you obviously cannot trust the users to have their system clock correctly set. (If the users have their timezone incorrectly set too, there is not really any solution; other than printing the current server time in "local" time)


You can use getUTCDate() and the related getUTC...() methods to access a time based off UTC time, and then convert.

If you wish, you can use valueOf(), which returns the number of seconds, in UTC, since the Unix epoch, and work with that, but it's likely going to be much more involved.


short answer from client-side: NO, you have to get it from the server side.


The best way to do this is to use getLocaleString, like this:

Create a date object:

date = new Date(0)

If you are in Berlin, this should convert to this string:

Thu Jan 01 1970 01:00:00 GMT+0100 (CET)

Get the hours in Athens:

date.toLocaleString('de-DE', {hour: '2-digit',   hour12: false, timeZone: 'Europe/Athens' })

'02'

Get the hours in Shanghai:

date.toLocaleString('de-DE', {hour: '2-digit',   hour12: false, timeZone: 'Asia/Shanghai' })

'08'


before you get too excited this was written in 2011

if I were to do this these days I would use Intl.DateTimeFormat. Here is a link to give you an idea of what type of support this had in 2011

original answer now (very) outdated

Date.getTimezoneOffset()

The getTimezoneOffset() method returns the time difference between Greenwich Mean Time (GMT) and local time, in minutes.

For example, If your time zone is GMT+2, -120 will be returned.

Note: This method is always used in conjunction with a Date object.

var d = new Date()
var gmtHours = -d.getTimezoneOffset()/60;
document.write("The local time zone is: GMT " + gmtHours);
//output:The local time zone is: GMT 11

The .getTimezoneOffset() method should work. This will get the time between your time zone and GMT. You can then calculate to whatever you want.


You could use Intl.DateTimeFormat.

_x000D_
_x000D_
let options = {_x000D_
    timeZone: 'Europe/London',_x000D_
    year: 'numeric',_x000D_
    month: 'numeric',_x000D_
    day: 'numeric',_x000D_
    hour: 'numeric',_x000D_
    minute: 'numeric',_x000D_
    second: 'numeric',_x000D_
  },_x000D_
  formatter = new Intl.DateTimeFormat([], options);_x000D_
_x000D_
console.log(formatter.format(new Date()));
_x000D_
_x000D_
_x000D_

Alternatively, if you're formatting just once instead of bulk use Date.prototype.toLocaleDateString().

(new Date()).toLocaleString([], options)

Unfortunately browsers are not required to understand timezones other than UTC, so try these blocks and figure out an alternative in case it fails, for example fetch the timezone offset from a server.


This is Correct way to get ##

function getTime(offset)
        {
            var d = new Date();
            localTime = d.getTime();
            localOffset = d.getTimezoneOffset() * 60000;

            // obtain UTC time in msec
            utc = localTime + localOffset;
            // create new Date object for different city
            // using supplied offset
            var nd = new Date(utc + (3600000*offset));
            //nd = 3600000 + nd;
            utc = new Date(utc);
            // return time as a string
            $("#local").html(nd.toLocaleString());
            $("#utc").html(utc.toLocaleString());
        }

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to time

Date to milliseconds and back to date in Swift How to manage Angular2 "expression has changed after it was checked" exception when a component property depends on current datetime how to sort pandas dataframe from one column Convert time.Time to string How to get current time in python and break up into year, month, day, hour, minute? Xcode swift am/pm time to 24 hour format How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time? What does this format means T00:00:00.000Z? How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift? Extract time from moment js object

Examples related to timezone

How to set the timezone in Django? How to convert Moment.js date to users local timezone? What does this format means T00:00:00.000Z? How do I get the current timezone name in Postgres 9.3? MySQL JDBC Driver 5.1.33 - Time Zone Issue Python get current time in right timezone Symfony2 and date_default_timezone_get() - It is not safe to rely on the system's timezone settings PHP date() with timezone? How to store a datetime in MySQL with timezone info Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST