JS日期格式化


JS 日期时间格式化

在前端项目中, 我们往往需要对新建的时间对象(如 new Date() )进行格式化, 将其转换为对用户友好的格式。

接下来简单列几个js时间格式化的方法吧, 如果你有更多更好的方法也可以分享一下哟 (^U^)ノ~

一、JS内置API

除了new Date().getDate()等最基本的API,其实还有其他帮助我们我们格式化日期时间的API。
例如JS内置 Intl.DateTimeFormat等API,可以帮助我们快速方便地格式化时间格式,而且Intl.DateTimeFormat这个API还可以用于i18n国际化。

console.log(new Intl.DateTimeFormat('en-US').format(date)); // "05/04/2021"

console.log(new Intl.DateTimeFormat('zh').format(date)); // "2021/05/04"

console.log(new Intl.DateTimeFormat('zh-GB', { dateStyle: 'full', timeStyle: 'long' }).format(date));
// "2021年5月4日星期日GMT+8 上午11:23:16"

二、自定义函数

formatDate = function (t, str) {
  const obj = {
      yyyy: t.getFullYear(),
      yy: ("" + t.getFullYear()).slice(-2),
      M: t.getMonth() + 1,
      MM: ("0" + (t.getMonth() + 1)).slice(-2), d: t.getDate(),
      dd: ("0" + t.getDate()).slice(-2), H: t.getHours(), HH: ("0" + t.getHours()).slice(-2),
      h: t.getHours() % 12,
      hh: ("0" + t.getHours() % 12).slice(-2),
      m: t.getMinutes(),
      mm: ("0" + t.getMinutes()).slice(-2), s: t.getSeconds(), ss: ("0" + t.getSeconds()).slice(-2),
      w: ['日', '一', '二', '三', '四', '五', '六'][t.getDay()]
    };
    return str.replace(/([a-z]+)/ig, function ($1) {
      return obj[$1]
      });
    };

使用方式

formatDate(new Date(),'yyyy-MM-dd HH:mm:ss') // "2021-05-04 19:10:57"

三、为Date原型添加format方法

Date.prototype.format = function(fmt) {
  var o = {
    "M+" : this.getMonth()+1,                 //月份
    "d+" : this.getDate(),                    //日
    "h+" : this.getHours(),                   //小时
    "m+" : this.getMinutes(),                 //分
    "s+" : this.getSeconds(),                 //秒
    "q+" : Math.floor((this.getMonth()+3)/3), //季度
    "S" : this.getMilliseconds()             //毫秒
  };
  if(/(y+)/.test(fmt)) {
    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
  }
  for(var k in o) {
    if(new RegExp("("+ k +")").test(fmt)){
    fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
  }
 }
 return fmt;
}

使用方式

const time = new Date().format("yyyy-MM-dd hh:mm:ss");
console.log(time);

四、第三方js库

没有什么不是引入一个js库不能解决的,如果有,那就再多来几个 🤪

可以使用 momentdayjs 等第三方js库,具体可以看相关文档。emmmm,真香

i18n国际化

但如果还涉及到多语言国际化i18n,除了 使用JS内置API Intl.DateTimeFormat 个人还是还是推荐使用第三方库,如 momentdayjs 等,方便省事 😃


文章作者: hjwforever
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 hjwforever !
评论
  目录