Reputation: 1000
As per I know,
var now = new Date();
var now_utc = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
It's based on client time machine.
Suppose, client machine has modified their time ahead or behind, then it will be a problem.
Please, correct me If I'm wrong.
Question - How can I get exact UTC/GMT time on client side if client time is ahead or behind?
Upvotes: 0
Views: 735
Reputation: 628
You can either use toISOString
function:
var utc = new Date().toISOString(); // 2015-05-26T04:30:09.490Z
Or create a new date by calculating the timezone offset
var now = new Date();
var utc = new Date(now.getTime() + now.getTimezoneOffset() * (60 * 1000));
Note that in above code getTimezoneOffset()
returns timezone in minutes. So, I am converting it in to milliseconds.
There is always moment-timezone library which simplifies dealing with timezones.
Upvotes: 2
Reputation: 950
If you want a solution independent of a user's clock, you have to use a web service of some sort. You can build your own (send your server's time to the browser), or use a web service.
Here is an example using timeapi.org, which returns and outputs the current time in GMT. You can modify this code to send the user's timezone as an offset instead (replace URL with something like http://www.timeapi.org/+10/now
where +10 is the offset).
<script type="text/javascript">
function myCallback(json) {
alert(new Date(json.dateString));
}
</script>
<script type="text/javascript" src="http://timeapi.org/utc/now.json?callback=myCallback"></script>
Lifted from this page.
Upvotes: 0