實現簡易版的moment.js

  代碼github地址:https://github.com/haozhaohang/librarygit

  做者: 易憐白github

 

  項目中使用了時間日期的處理方法,只使用了部分方法,爲了避免在引入第三方的庫(moment.js),這裏本身封裝了項目中使用到的方法。this

  要實現如下功能: spa

new Moment()
// 返回當前的時間對象

new Moment().unix() // 返回當前時間的秒數  Moment.unix(timestamp) // 傳入秒數,返回傳入秒數的時間對象 new Moment().format('YYYY-MM-DD dd HH:mm:ss') // 返回值 2017-06-22 四 19:46:14  Moment.unix(1498132062000).format('YYYY-MM-DD dd HH:mm:ss') // 返回值 2017-06-22 四 19:46:14

 

  1、基礎代碼:unix

1 class Moment {
2     constructor(arg = new Date().getTime()) { 3 this.date = new Date(arg) 4  } 5 }

  arg = new Date().getTime() :這裏使用解構對arg添加默認值 code

 

  2、實現unix方法orm

 1 class Moment {
 2     constructor(arg = new Date().getTime()) { 3 this.date = new Date(arg) 4  } 5 6 // getTime()返回的是毫秒數,須要轉成秒數並取整 7  unix() { 8 return Math.round(this.date.getTime() / 1000) 9  } 10 }

  unix方法:返回當前時間的秒數對象

  getTime()方法返回的是毫秒數須要除1000取整處理blog

 

  3、實現靜態unix方法get

1 class Moment {
2     constructor(arg = new Date().getTime()) { 3 this.date = new Date(arg) 4  } 5 6  static unix(timestamp) { 7 return new Moment(timestamp * 1000) 8  } 9 }

  靜態unix方法:參數timestamp 毫秒數  返回一個Date對象

  new Date()只能接受毫秒的參數須要乘1000

  

  4、實現format方法

 1 class Moment {
 2     constructor(arg = new Date().getTime()) { 3 this.date = new Date(arg) 4  } 5 6  format(formatStr) { 7 const date = this.date 8 const year = date.getFullYear() 9 const month = date.getMonth() + 1 10 const day = date.getDate() 11 const week = date.getDay() 12 const hour = date.getHours() 13 const minute = date.getMinutes() 14 const second = date.getSeconds() 15 16 return formatStr.replace(/Y{2,4}|M{1,2}|D{1,2}|d{1,4}|H{1,2}|m{1,2}|s{1,2}/g, (match) => { 17 switch (match) { 18 case 'YY': 19 return String(year).slice(-2) 20 case 'YYY': 21 case 'YYYY': 22 return String(year) 23 case 'M': 24 return String(month) 25 case 'MM': 26 return String(month).padStart(2, '0') 27 case 'D': 28 return String(day) 29 case 'DD': 30 return String(day).padStart(2, '0') 31 case 'd': 32 return String(week) 33 case 'dd': 34 return weeks[week] 35 case 'ddd': 36 return '周' + weeks[week] 37 case 'dddd': 38 return '星期' + weeks[week] 39 case 'H': 40 return String(hour) 41 case 'HH': 42 return String(hour).padStart(2, '0') 43 case 'm': 44 return String(minute) 45 case 'mm': 46 return String(minute).padStart(2, '0') 47 case 's': 48 return String(second) 49 case 'ss': 50 return String(second).padStart(2, '0') 51 default: 52 return match 53  } 54  }) 55  } 56 }

  format方法: 傳入'YYY-MM-DD HH:mm:ss','YYY-MM-DD' 等,根據本身的傳入要獲取的格式(具體可參看moment.js的format的方法)

  padStart()方法爲月份或日期前補0

  

  到這裏咱們就實現了unix,靜態unix,format三個方法,完成代碼能夠去查看github,若是須要實現其它的日期時間處理方法能夠給我留言,後面我會慢慢完善添加。

相關文章
相關標籤/搜索