JS 时间工具类

获取时区

export function getOffset = () => {
    const offset = (new Date()).getTimezoneOffset() / 60;
    if (offset < 0) {
      return Math.abs(offset);
    }
    return -offset;
  }

验证日期是否是今天

export function isToday(str) {
  const today = new Date();
  const sendDate = new Date(str);
  if (today.getFullYear() === sendDate.getFullYear() &&
    today.getMonth() === sendDate.getMonth() &&
    today.getDate() === sendDate.getDate()) {
    return true;
  }
  return false;
}

验证日期是否是昨天

export function isYesterday(str) {
  const yesterday = (new Date()).getTime() - (1000 * 60 * 60 * 24);
  const sendDate = new Date(str);
  if (yesterday.getFullYear() === sendDate.getFullYear() &&
    yesterday.getMonth() === sendDate.getMonth() &&
    yesterday.getDate() === sendDate.getDate()) {
    return true;
  }
  return false;
}

判断中午/下午(AM/PM)

export function getNowTime(str) {
  const lan = getlocalLanguge();
  const d = new Date(str);
  let hours = d.getHours();
  if (lan === 'zh') {
    let noon = '上午';
    if (hours > 12) {
      hours -= 12;
      noon = '下午';
    }
    return `${fixedZero(hours)}:${fixedZero(d.getMinutes())} ${noon}`;
  }
  let noon = 'AM';
  if (hours > 12) {
    hours -= 12;
    noon = 'PM';
  }
  return `${fixedZero(hours)}:${fixedZero(d.getMinutes())} ${noon}`;
}

时间戳转换时间

export function timestampToTime(timestamp) {
  const date = new Date(timestamp);// 时间戳为10位需*1000,时间戳为13位的话不需乘1000
  const Y = `${date.getFullYear()}-`;
  const M = `${date.getMonth() + 1 < 10 ? `0${date.getMonth() + 1}` : date.getMonth() + 1}-`;
  const D = `${date.getDate()} `;
  const h = `${date.getHours()}:`;
  const m = `${date.getMinutes()}:`;
  const s = date.getSeconds();
  return Y + M + D + h + m + s;
}

获取当前时间的时分秒
(通过moment插件,moment地址:http://momentjs.cn/)

export const getHMSDate = () => { // get current date hours、minutes、seconds
  return `${moment().hours()}:${moment().minutes() > 10 ? moment().minutes() : `0${moment().minutes()}`}:${moment().seconds() > 10 ? moment().seconds() : `0${moment().seconds()}`}`
}

js:

const myDate = new Date();
export const getHMSDate = () => { // get current date hours、minutes、seconds
  return `${myDate.getHours()}:${myDate.getMinutes() > 10 ? myDate.getMinutes() : `0${myDate.getMinutes()}`}:${myDate.getSeconds() > 10 ? myDate.getSeconds() : `0${myDate.getSeconds()}`}`
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值