What is the best method to get the clients local time irrespective of the time zone of clients system? I am creating an application and i need to first of all get the exact time and date of the place from where the client is accessing. Even detecting the ip address of client system has a drawback or detecting the time zone of client system may be risky at times. So, is there any way out which could be really reliable and not vulnerable to error because displaying wrong time and date to client is something very embarassing.
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to fix IE ClearType + jQuery opacity problem i
- void before promise syntax
- jQuery add and remove delay
In JavaScript? Just instantiate a new Date object
That will create a new Date object with the client's local time.
my code is
if you want more codes visit my blog http://mysimplejavascriptcode.blogspot.in/
The most reliable way I've found to display the local time of a city or location is by tapping into a Time Zone API such as Google Time Zone API. It returns the correct time zone, and more importantly, Day Light Savings Time offset of any location, which just using JavaScript's Date() object cannot be done as far as I'm aware. There's a good tutorial on using the API to get and display the local time here:
From: Displaying the Local Time of Any City using JavaScript and Google Time Zone API
Nowadays you can get correct timezone of a user having just one line of code:
source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/resolvedOptions
You can then use moment-timezone to parse timezone like:
Try on this way
is a function to change the date time format like
toLocaleDateString("en-us")
Just had to tackle this so thought I would leave my answer. jQuery not required I used to update the element as I already had the object cached.
I first wrote a php function to return the required dates/times to my HTML template
This is then used in my HTML template to display an initial time, and render the date format required by javascript in a data attribute.
I then used the getUTCHours on my date object to return the time irrespective of the users timezone
I then use the setSeconds method to update the date object based on the amount of seconds past since page load (simple interval function), and update the HTML