date-fns#getTime TypeScript Examples

The following examples show how to use date-fns#getTime. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: rank.ts    From ncov with MIT License 6 votes vote down vote up
getChinaDay = async (socket: any, data: any, channel: string, eventName: string) => {
    axios.get('https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5&callback=')
        .then(async (res: any) => {
            if (res.ret === 0) {
                const allData = JSON.parse(res.data || {});
                const chinaDayList = allData.chinaDayList;
                await _pushSuccess(channel, eventName, chinaDayList, getTime(new Date())); // timeline 折线图
                res = null
            }
        })
        .catch((err: any) => {
            console.info('getChinaDay', err);
        })
}
Example #2
Source File: socket.ts    From ncov with MIT License 6 votes vote down vote up
connectSocket = async (socket: any) => {
    const {id, handshake} = socket;
    const {issued} = handshake;
    const {sid} = _sid_obj(id);
    await insertOne({..._sid_obj(id), noAuthCount: 1, beginTime: issued}, 'sockets');
    await setSet('onlineSocket', sid);
    await _pushSuccess('broadcast', 'online', await totalOnline('onlineSocket'));
    socket.on('disconnect', async () => {
        const {id} = socket;
        await delSet('onlineSocket', sid);
        await updateOne({sid}, {..._sid_obj(id), endTime: getTime(new Date())}, 'sockets');
        await delKey(sid);
        await _pushSuccess('broadcast', 'online', await totalOnline('onlineSocket'));
    })
}
Example #3
Source File: talk.ts    From ncov with MIT License 6 votes vote down vote up
talkIn = async (socket: any, sid: string, data: string, channel: string, eventName: string) => {
    await _authUser(socket, sid, data, channel, eventName, 'noAuth'); // 非登录用户
    const redisObj: any = await getHash(sid) || {};
    const talkInObj: any = {
        sid,
        name: redisObj ? redisObj.name : "",
        avatarUrl: redisObj ? redisObj.avatar_url : "",
        isAdmin: redisObj ? redisObj.isAdmin : false,
        message: data,
        channel: channel,
        eventName,
        createTimestamp: getTime(new Date())
    };
    const {_id}: any = await insertOne(talkInObj, 'barrages'); //todo 后面需要放开的
    talkInObj._id = _id;
    await _pushSuccess('broadcast', 'talk', talkInObj, 'talking');
}
Example #4
Source File: PastTimePicker.stories.tsx    From gio-design with Apache License 2.0 5 votes vote down vote up
Since.args = {
  value: `since:${getTime(subDays(startOfToday(), 7))}`,
};
Example #5
Source File: PastTimePicker.stories.tsx    From gio-design with Apache License 2.0 5 votes vote down vote up
Absolute.args = {
  value: `abs:${getTime(subMonths(startOfToday(), 1))},${getTime(startOfToday())}`,
  onRangeSelect: (date: any, index: number) => console.log(date, index)
};
Example #6
Source File: AbsoluteRangePicker.tsx    From gio-design with Apache License 2.0 5 votes vote down vote up
function AbsoluteRangePicker({ disabledDate, timeRange, onSelect, onRangeSelect, onCancel }: RangePickerProps) {
  const [dates, setDates] = React.useState<[Date | undefined, Date | undefined]>(parseStartAndEndDate(timeRange));
  const prefixCls = usePrefixCls('range-panel__header');

  const locale = useLocale('StaticPastTimePicker');

  const { startDayText, endDayText, FromText, ToText } = {
    ...defaultLocale,
    ...locale,
  };

  const renderHeader = () => {
    const placeholder = [startDayText, endDayText];
    const dateString = formatDates(dates);
    const dateTexts = dateString?.split('-')?.map((d) => (d === ' ' ? undefined : d)) || [];
    const text = [dateTexts[0] ?? placeholder[0], dateTexts[1] ?? placeholder[1]];
    return <span className={`${prefixCls}__text`}>{`${FromText} ${text[0]} ${ToText} ${text[1]}`}</span>;
  };
  const handleDisabledDate = (current: Date) => disabledDate?.(current) || isAfter(current, startOfToday());
  const handleOnOK = () => {
    onSelect(`abs:${getTime(startOfDay(dates[0] as Date))},${getTime(endOfDay(dates[1] as Date))}`);
  };
  const handleOnSelect = (date: [Date, Date], index: number) => {
    setDates(date);
    onRangeSelect?.(date, index);
  }
  const endDay = dates[1] !== undefined && isValid(dates[1]) ? dates[1] : new Date();
  return (
    <InnerRangePanel
      disableOK={!isValid(dates[0]) || !isValid(dates[1])}
      header={renderHeader()}
      body={
        <StaticDateRangePicker
          defaultViewDates={[subMonths(startOfDay(endDay), 1), startOfDay(endDay)]}
          disabledDate={handleDisabledDate}
          onSelect={handleOnSelect}
          value={dates as [Date, Date]}
        />
      }
      onCancel={onCancel}
      onOK={handleOnOK}
    />
  );
}
Example #7
Source File: SinceRangePicker.tsx    From gio-design with Apache License 2.0 5 votes vote down vote up
function SinceRangePicker({ disabledDate, timeRange, onSelect, onCancel, experimental, ...rest }: RangePickerProps) {
  const endDateKeys = ['today', experimental ? 'yesterday' : undefined];
  const dates = parseStartAndEndDate(timeRange);
  const prefixCls = usePrefixCls('range-panel__header');
  const [startDate, setStartDate] = React.useState<Date | undefined>(dates[0]);
  const [endKey, setEndKey] = React.useState(
    endDateKeys[timeRange && timeRange.split(':')[0] === 'since' ? 0 : 1] || 0
  );
  const locale = useLocale<typeof defaultLocale>('StaticPastTimePicker') || defaultLocale;

  const { startDayText, FromText, toTodayText, toYesterdayText } = {
    ...defaultLocale,
    ...locale,
  };

  const END_DATE_MAPPING: Record<string, string> = {
    today: toTodayText,
    yesterday: toYesterdayText,
  };

  const renderHeader = () => {
    const startDateString = startDate ? format(startDate, DATE_FORMAT) : startDayText;
    return (
      <>
        <span className={`${prefixCls}__text`}>{`${FromText} ${startDateString}`}</span>
        <span className={`${prefixCls}__options`}>
          <Switch
            size="small"
            defaultValue={endKey}
            onChange={(e) => {
              setEndKey(e.target.value);
            }}
          >
            {endDateKeys.map(
              (o: string) =>
                o && (
                  <Switch.Item key={o} value={o}>
                    {END_DATE_MAPPING[o]}
                  </Switch.Item>
                )
            )}
          </Switch>
        </span>
      </>
    );
  };
  const handleDisabledDate = (current: Date) =>
    disabledDate?.(current) || isAfter(current, endKey === 'yesterday' ? startOfYesterday() : startOfToday());

  const handleOnOK = () => {
    onSelect(`${endKey === 'yesterday' ? 'since-lt-today' : 'since'}:${getTime(startOfDay(startDate as Date))}`);
  };
  return (
    <InnerRangePanel
      disableOK={!isValid(startDate)}
      header={renderHeader()}
      body={<DatePicker disabledDate={handleDisabledDate} value={startDate} onSelect={setStartDate} />}
      onCancel={onCancel}
      onOK={handleOnOK}
      {...rest}
    />
  );
}
Example #8
Source File: report.ts    From ncov with MIT License 5 votes vote down vote up
report = async (socket: any, sid: string, data: any, channel: string, eventName: string) => {
    // 非登录用户直接打断
    await _authUser(socket, sid, data, channel, eventName, 'noAuth'); // 非登录用户
    const reqData: ReportInterface.insert = data;
    let logType = '';
    if (isObject(reqData)) {
        // 先确认必填项,校验时间类型
        if (reqData.country && reqData.province && reqData.reportDate && isString(reqData.reportDate) && reqData.newsUrl && (reqData.count || reqData.cure || reqData.dead || reqData.suspected)) {
            logType = 'success';
            let redisObj: any = await getHash(sid);
            const passObj: any = {};
            redisObj = {};
            if (!redisObj) {
                return
            } else {
                // 补充信息
                reqData.githubName = redisObj.name;

                // 尝试转换时间格式
                if (isString(reqData.reportDate)) {
                    reqData.reportDate = getTime(new Date(reqData.reportDate))
                }

                // 插入audits 数据库
                let auditData: any = await insertOne({
                    ...data,
                    sid,
                    count: reqData.count || 0,
                    cure: reqData.dead || 0,
                    suspected: reqData.cure || 0,
                    dead: reqData.suspected || 0
                }, 'audits');


                // 拆开count、dead、cure 治愈
                await insertForReport(reqData.count, {
                    ...reqData,
                    sid,
                    auditId: auditData._id,
                    isConfirm: true, ...passObj
                }, sid, 'reports', redisObj.name);
                await insertForReport(reqData.dead, {
                    ...reqData,
                    sid,
                    auditId: auditData._id,
                    isDead: true, ...passObj
                }, sid, 'reports', redisObj.name);
                await insertForReport(reqData.cure, {
                    ...reqData,
                    sid,
                    auditId: auditData._id,
                    isCure: true, ...passObj
                }, sid, 'reports', redisObj.name);
                await insertForReport(reqData.suspected, {
                    ...reqData,
                    sid,
                    auditId: auditData._id,
                    isSuspected: true, ...passObj
                }, sid, 'reports', redisObj.name);
                await _pushSuccess('broadcast', 'console', data, '下发审核数据'); // 推送到前端console
                await logSocket(socket, data, channel, eventName, logType);
                return await _pushSuccess(channel, eventName, [], '已收录,谢谢你的贡献,管理员审核通过后将采用', 0,)
            }
        }
        await logSocket(socket, data, channel, eventName, logType);
        return await _pushError(channel, eventName, reqData, '无效数据');
    }
}
Example #9
Source File: task.ts    From ncov with MIT License 5 votes vote down vote up
rankTask = async (dateStr?: string | null) => {
    let reportDateObj: any = {};
    if (dateStr && new Date(dateStr)) {
        reportDateObj.reportDate = getTime(new Date(dateStr))
    }
    let auditList = await getRankAll({pass: true, country: "中国", ...reportDateObj}, [
        "count", "cure", "dead", "suspected",
        'country', 'province'], 'audits') || [];
    let provinceObj: any = {};
    auditList.map((item: any) => {
        if (!provinceObj[item.province]) {
            provinceObj[item.province] = {
                count: 0,
                cure: 0,
                dead: 0,
                suspected: 0
            }
        }
        provinceObj[item.province].count += (item.count || 0);
        provinceObj[item.province].cure += (item.cure || 0);
        provinceObj[item.province].dead += (item.dead || 0);
        provinceObj[item.province].suspected += (item.suspected || 0);
        provinceObj[item.province].province = item.province || "";
        provinceObj[item.province].country = item.country || ""
    });

    let rankList = [];
    for (let item in provinceObj) {
        delete provinceObj[item]._id;
        rankList.push(provinceObj[item])
    }

    rankList.sort((left: any, right: any) => {
        if (left.count > right.count) {
            return 1
        }
        if (left.count < right.count) {
            return -1
        }
        return 0
    });

    return rankList

}
Example #10
Source File: task.ts    From ncov with MIT License 5 votes vote down vote up
tencent = async (dateStr?: number | string | null) => {
    axios.get('https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5&callback=')
        .then(async (res: any) => {
            if (res.ret === 0) {
                const allData = JSON.parse(res.data || {});
                const totalData = parseTotal(allData.chinaTotal, allData.areaTree.slice(1), allData.lastUpdateTime);
                const worldMapData = parseWorldMap(allData.areaTree);
                const chinaRank = parserChinaRank(allData.areaTree[0]);
                const worldRank = parseWorldRank(allData.areaTree);
                const chinaDayList = allData.chinaDayList;
                // 处理history部分
                const fullYear = new Date().getFullYear();
                const fullMouth = new Date().getMonth() + 1; //0月开始
                const fullDay = new Date().getDate();
                const fullHour = new Date().getHours();
                const fullMinute = new Date().getMinutes();
                const date = fullYear + '-' + (fullMouth + '').padStart(2, '0') + '-' + String(fullDay - 1).padStart(2, '0'); // 昨天的日期
                const today = fullYear + '-' + (fullMouth + '').padStart(2, '0') + '-' + String(fullDay).padStart(2, '0'); // 今天的日期

                // 0时10分前,更新数据,以存储历史数据,这个会有误差
                if (fullHour < 1 && fullMinute < 10) {
                    await updateOne({
                        date,
                        totalData,
                        worldMapData,
                        chinaRank,
                        worldRank,
                        chinaDayList
                    }, {}, 'historys');
                    await setHash(date.toString(), {date: date.toString()})
                }
                let redisTotalData: any = await getHash(today);
                if (!redisTotalData) {
                    redisTotalData = {}
                }
                const redisTotal = redisTotalData.totalData || "{}";
                const {worldConfirm, worldHeal, worldDead, worldSuspect} = JSON.parse(redisTotal);
                // 检查不相同,则推送到前端
                if (!redisTotalData.totalData || worldConfirm !== totalData.worldConfirm || worldHeal !== totalData.worldHeal &&
                    worldDead !== totalData.worldDead || worldSuspect !== totalData.worldSuspect) {
                    //  延时推送,以免一次性数据量太大
                    await _pushSuccess('broadcast', 'getTotal', totalData, 'push'); // 统计
                    await _pushSuccess('broadcast', 'getWorldRank', worldRank, getTime(new Date())); // 世界rank
                    await _pushSuccess('broadcast', 'getChinaDay', chinaDayList, getTime(new Date())); // timeline 折线图
                    await _pushSuccess('broadcast', 'getChinaRank', chinaRank, getTime(new Date())); // 国内rank
                    await _pushSuccess('broadcast', 'getWorldMap', worldMapData, getTime(new Date())); // 世界地图
                    await setHash(today, {totalData: JSON.stringify(totalData || {})});
                }
                res = null
            }
        })
}