获取北京本地时间(已封装,即开即用)

前言

各位还记得之前我们一起搞的那个计时器嘛~带你撸一个精准倒计时
这里我们提到了另一种思路,使用网上的服务器时间来获取精准计时。为什么我们需要使用网络上的计时器呢?因为 new Date() 获取的是客户端本地的服务,如果我们要做秒杀等活动的话,用户手动修改手机时间,是不是就会出现很多的问题。

解决思路

image.png

我们之前的方案是使用第一种解决方法。最近我吧另外一种的核心(获取当地时间)给大家封装好了。代码如下:

import axios from "axios";
// https://www.jsjiami.com/article/get-now-time.html
const apiList = {
  TB: 'http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp',
  SN: 'https://f.m.suning.com/api/ct.do',
  JD: 'https://a.jd.com//ajax/queryServerData.html',
  TX: 'http://vv.video.qq.com/checktime?otype=json'
};

class NowTimeClass {
  constructor(origin = 'TB') {
    this.time = '';
    this.apiList = apiList;
    this.api = apiList[origin];
    this.origin = origin;
    this.timestamp = '';
  }

  async getNetWorkTime() {
    let timestamp = '',
      res = '';
    res =
      this.origin === 'SN'
        ? await axios.get(this.api)
        : await axios.post(this.api);
    switch (this.origin) {
      case 'TB':
        timestamp = res.data.data.t;
        break;
      case 'SN':
        timestamp = res.data.currentTime;
        break;
      case 'JD':
        timestamp = res.data.serverTime;
        break;
      case 'TX':
        // 腾讯返回的字符串,我们需要截取一下
        let num = res.data.indexOf('"t":');
        timestamp = res.data.slice(num + 4, num + 14);
        break;

      default:
        timestamp = new Date().getTime();
        break;
    }
    this.timestamp = timestamp;
  }

  async getTime() {
    await this.getNetWorkTime();
    console.log(this.timestamp);
    return this.timestamp;
  }
}

function getNowTime(origin) {
  return new NowTimeClass(origin);
}

export default getNowTime;

使用方法:

    let getNowTime = new getNowTime()
    let timestamp = getNowTime.getTime()

一个很简单的调用,思想就是获取大厂提供的时间api,得到数据之后进行一次format。