When the JS-time conversion

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/u012193330/article/details/79637660

Business scene:

Page server time is eight districts in Eastern Time, page JS functions need to compare server time and local time users, is compatible with the rest of the world the time, we need to convert the user's local time zone as the East eight times.

basic concept

Greenwich Mean Time

When time is called GMT place on the Greenwich meridian, or zero zone (time zone) of the region, also known as the world. (For more detailed concepts do not say, we do not need here.) For example, we Chinese are eight districts in the East, Beijing is (GMT + 08: 00)

Get local and GMT time difference of: new new a Date () getTimezoneOffset (), in minutes.

GMT is known, in terms of the correct local time

Local Time = Greenwich Mean Time - the time difference

Local time is known, the corresponding conversion GMT:

Local time = GMT + time difference

It is known local time, in terms of time in other time zones

Because the difference is based on the time interval in units of hours. So after the 0:00 time zone is calculated, minus or plus the corresponding hour (Eastern District N + N then hours, then the Western District N -N hours). For ease of calculation, the East region denoted a positive number N, N Western region denoted negative, namely: a target time zone difference + = + local time zone time interval

Example: Convert local time to Eastern time eight districts

var timezone = 8; //目标时区时间,东八区
var offset_GMT = new Date().getTimezoneOffset(); // 本地时间和格林威治的时间差,单位为分钟
var nowDate = new Date().getTime(); // 本地时间距 1970 年 1 月 1 日午夜(GMT 时间)之间的毫秒数
var targetDate = new Date(nowDate + offset_GMT * 60 * 1000 + timezone * 60 * 60 * 1000);
console.log("东8区现在是:" + targetDate);

Guess you like

Origin blog.csdn.net/u012193330/article/details/79637660