Is there any way to do this in angular js
or just javascript
? Getting a time that does not depend on the local date of the PC? The only solution I could think of was to constantly make requests to the back-end so it would use the server's time and not the client-side local time but it's not really a solution as it would require to constantly make requests, which clearly sucks as it's a brute force method that doesn't really yield the desired result since the requests obviously have delay.
Asked
Active
Viewed 2,563 times
0

Sachin Mokashi
- 415
- 5
- 17

Baek Ryun
- 100
- 1
- 3
- 14
-
ECMA-262 doesn't specify where date and time values come from, so they can be sourced from anywhere. However, they most likely come from current system settings, so `new Date()` will be based on whatever the host says is the current date, time and timezone offset. The host may use a time server, or just whatever the user has set it too. I often change the settings for testing, they are not necessarily accurate. – RobG Dec 01 '16 at 12:45
2 Answers
1
//converts local time to UTC (Universal Time)
function toUTC(/*Date*/date) {
return Date.UTC(
date.getFullYear()
, date.getMonth()
, date.getDate()
, date.getHours()
, date.getMinutes()
, date.getSeconds()
, date.getMilliseconds()
);
} //toUTC()
This function will give you the unix epoch ticks in UTC (thanks to: http://blog.davidjs.com/2011/05/convert-local-time-to-utc-time-in-javascript/)
If you need to display this in a user friendly way please consult the reference: http://www.w3schools.com/jsref/jsref_obj_date.asp
Good luck!

Ali Kareem Raja
- 566
- 1
- 7
- 21
-
This treats the local date as if it were UTC, which does not seem like a good idea. It will produce a different result for the same instant in time for each time zone with a different offset. I don't think it answers the OP, which seems to be asking how to get an accurate date and time from a host. – RobG Dec 01 '16 at 12:43
0
Calling the Date constructor with no arguments creates an object that contains the time of day and date at the moment it was called, and that contains all the information needed to calculate the UTC time. Then it is simply a matter of choosing methods that will output UTC time rather than local time. For example:
<!DOCTYPE html>
<html>
<body>
<h1>Display present UTC time</h1>
<script>
var d = new Date();
document.writeln( d.toUTCString());
</script>
</body>
</html>

Gerard Ashton
- 560
- 4
- 16