0

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?

korrawit
  • 1,000
  • 2
  • 18
  • 30
  • `new Date().getTimezoneOffset()` will give you the offset timezone in minutes. To make in to hours, check this [link](http://stackoverflow.com/a/30377368/1577396) – Mr_Green May 26 '15 at 04:36

2 Answers2

2

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.

Mr_Green
  • 40,727
  • 45
  • 159
  • 271
eymen
  • 628
  • 6
  • 17
0

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.

Simon
  • 937
  • 1
  • 8
  • 25