分享

获取各维度下的开始时间并格式化

 精品唯居 2022-12-25 发布于北京
最近开发需要,用js获得当日、本月、当年的开始时间,并进行格式化为
yyyy-MM-dd hh:mm:ss
/**
 *格式化时间
 *yyyy-MM-dd hh:mm:ss
 */
formatDate(time, fmt) {
  if (time === undefined || '') {
    return
  }
  const date = new Date(time)
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  const o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  }
  for (const k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      const str = o[k] + ''
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : padLeftZero(str))
    }
  }
  return fmt
}
    const now = new Date();
      const fmt = 'yyyy-MM-dd 00:00:00';
      // 当日开始时间
      const dayStart = formatDate(now, fmt);
      // 当前时间
      const dayNow = formatDate(now, 'yyyy-MM-dd hh:mm:ss');
      // 当月开始时间
      const m = now.setDate(1);
      const monthStart = formatDate(m, fmt);
      // 当年开始时间
      const y = now.setMonth(0);
      const yearStart = formatDate(y, fmt);
      console.log(dayStart);
      console.log(dayNow);
      console.log(monthStart);
      console.log(yearStart);
 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多