Kselax.ru

Hacker Kselax – the best hacker in the world

Menu
  • Blog
  • Contacts
  • wp plugin generator
  • English
    • Русский
Menu
time zones

How to calculate the timezone in JavaScript

Posted on 20 July, 201830 July, 2018 by admin

Our world is divided into 24 time zones by Grinvitch, it calls GTC. The clients can be in different time zones. Sometimes we have to put the time that is saved on a server to clients. So the question is how we have to calculate the right time?

# How to save time on a server with the right time zone.

In JavaScript exists special object Date. First of all, we have to get a date

1
var date = new Date();

then get the timestamp

1
var timestamp = date.getTime();

and offset

1
var offset = date.getTimezoneOffset();

remember that getTimezoneOffset return the offset in minutes and our timestamp is in milliseconds. We have to convert our offset by multiple on 60 * 1000

Now we have to save the date on the server. The data equal the timestamp plus the offset

1
var gr = timestamp + offset;

Or we can save the offset with the timestamp without calculation gr. Gr means Grinvitch.

 

# How to get the correct data on the client from the server?

On the client, we get a timestamp gr or timestamp with the server offset. Suppose we get the date gr. On the client, we have to do substruct with the current offset of the client to get the proper date.

1
timestamp = gr - offset;

 

to convert a timestamp to time we use Date

1
var date = new Date(timestamp);

 

That’s it.

 

# Formulas for calculation timestamp

1
new_timestamp =  timestamp + (offset1 - offset2);

we can use this on a server save by

1
timestamp = timestamp + offset;

and on a client calculate

1
timestamp = timestamp - offset;

 

 

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Categories

  • bash (1)
  • English (9)
  • JavaScript (4)
  • node.js (22)
  • photoshop (1)
  • php (3)
  • React (9)
  • sclerotic (6)
  • Ubuntu (10)
  • Uncategorized (15)
  • Wordpress (1)

Tags

Ajax apache2 automation bash chrome-extension command line editor ejs email English English-grammar framework functions git graphql handlebars hybrid app installation javascript js linux newbie node.js node.js javascript nodemailer npm objects Performance php phpmyadmin playonlinux promise rabbitmq React react-router redis reverse-proxy session shell socket.io sublime text 3 time zones ubuntu unity webpack

Recent Comments

  • damien on How to install npm and nodejs the latest versions on ubuntu
  • Cam on How to install npm and nodejs the latest versions on ubuntu
  • Pierre on socket.io with apache as a reverse proxy on the CentOS
  • admin on How to use react-router with a few languages
  • admin on How to install npm and nodejs the latest versions on ubuntu
©2021 Kselax.ru Theme by ThemeGiant