中国标准时间转换为年月日时分秒,指定00:00:00 或23:59:59或当下时分秒

每次写时间转化问题都好痛苦,花费巨大时间理清关系后,下次再写又忘了。好记性不如烂笔头,记录下来,方便下次翻阅。

1.中国标准时间转换为标准年月日时分秒的调用方法如下

export function formatDate(date, fmt) {
  if(!date){
    return '';
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
  }
  let o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  };
  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      let str = o[k] + '';
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
    }
  }
  return fmt;
};

function padLeftZero(str) {
  return ('00' + str).substr(str.length);
}

2.中国标准时间转换为年月日当天的凌晨00:00:00,具体调用方法如下

const time = new Date();

console.log(time)//输出结果 : Wed Jan 12 2022 11:01:17 GMT+0800 (中国标准时间)

const end = formatDate(new Date(), "yyyy-MM-dd 00:00:00");

console.log(end)//输出结果  : 2022-01-12 00:00:00

3.中国标准时间转换为年月日当天的23:59:59,具体调用方法如下

const time = new Date();

console.log(time)//输出结果 : Wed Jan 12 2022 11:01:17 GMT+0800 (中国标准时间)

const end = formatDate(new Date(), "yyyy-MM-dd 23:59:59");

console.log(end)//输出结果  : 2022-01-12 23:59:59

4.中国标准时间转换为年月日时分秒,具体调用方法如下

const time = new Date();

console.log(time)//输出结果 : Wed Jan 12 2022 11:01:17 GMT+0800 (中国标准时间)

const end = formatDate(new Date(), "yyyy-MM-dd hh:mm:ss");

console.log(end)//输出结果  : 2022-01-12 11:01:17

  • 10
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值