打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
获取各维度下的开始时间并格式化
最近开发需要,用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);
 
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
js Date格式化为yyyy-mm-dd类字符串
jstl 格式化时间,数字方法集合
JavaScript 中如何将日期格式化为 DD/MM/YYYY
javascript Date format(js日期格式化)
javascript中如何将字符串转化成日期&&日期格式化方法
js日期格式化
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服