-1

Trying to get the current time in JavaScript in Shanghai for a small project. Anyone know the easiest way to do this?

Kirk Ouimet
  • 27,280
  • 43
  • 127
  • 177
  • 1
    If you know the timeozone offset, you can work it out fairly easily, e.g. [The Google Time Zone API](https://developers.google.com/maps/documentation/timezone/) – RobG Nov 06 '13 at 01:58
  • In my defense, I did Google it and found nothing ;) – Kirk Ouimet Nov 06 '13 at 02:00
  • _I did Google it and found nothing_ Oh really? Did you try googling your exact title? –  Nov 06 '13 at 02:03
  • @Kirk—[https://www.google.com.au/?gfe_rd=ctrl&ei=nKN5UpBi68LyB97BgMgE&gws_rd=cr#q=web+time+service](https://www.google.com.au/?gfe_rd=ctrl&ei=nKN5UpBi68LyB97BgMgE&gws_rd=cr#q=web+time+service). – RobG Nov 06 '13 at 02:03
  • See: http://stackoverflow.com/a/15171030/2864740 ,.http://stackoverflow.com/questions/8207655/how-to-get-time-of-specific-timezone-using-javascript?rq=1 – user2864740 Nov 06 '13 at 02:06

3 Answers3

3

I used moment.js like a lazy bum:

var now = moment();
var timeInShanghai = now.tz('Asia/Shanghai').format('h:mma');
Kirk Ouimet
  • 27,280
  • 43
  • 127
  • 177
1

The entire of China has one timezone, which is UCT+08:00. So if you want the current time in Shanghai based on the host's system settings, get the local time, add the timezone offset (ECMAScript timezone offset is minutes to add to get UTC so UTC+10:00 is -600), then add the offset for Shanghai:

function timeInShanghai() {
  function z(n){return (n<10?'0':'') + n}
  var d = new Date();
  d.setMinutes(d.getMinutes() + d.getTimezoneOffset() + 480);
  return z(d.getHours()) + ':' + z(d.getMinutes()) + ':' + z(d.getSeconds());
}

A bit useless though if they change the timezone or adopt daylight saving.

RobG
  • 142,382
  • 31
  • 172
  • 209
0

The timezone offset of Shanghai is 8 To get the date:

var date=new Date().getTime();

to get the hours,minutes,seconds

seconds=parseInt((d/1000)%60);

hours=parseInt((d/(1000*60*60))%60)+8; \\for the offset

minutes=parseInt((d/(1000*60))%60);

and to put it back together as a string:

console.log(hours+":"+minutes+":"+seconds);
scrblnrd3
  • 7,228
  • 9
  • 33
  • 64
  • Of course you could always use the built–in getHours, getMinutes and getSeconds methods of Date instances. The above will get the hours wrong after 1600 UTC. – RobG Nov 06 '13 at 02:46