>  기사  >  웹 프론트엔드  >  moment.js 구현 예시에 대한 자세한 설명

moment.js 구현 예시에 대한 자세한 설명

零下一度
零下一度원래의
2017-06-23 10:42:282352검색

프로젝트에서는 시간 및 날짜 처리 방법을 사용하며, 타사 라이브러리(moment.js)를 도입하지 않기 위해 일부 방법만 여기에 캡슐화합니다.

다음 기능을 달성하려면:

new Moment()
// 返回当前的时间对象

new Moment().unix()
// 返回当前时间的秒数Moment.unix(timestamp)
// 传入秒数,返回传入秒数的时间对象

new Moment().format('YYYY-MM-DD dd HH:mm:ss')
// 返回值 2017-06-22 四 19:46:14Moment.unix(1498132062000).format('YYYY-MM-DD dd HH:mm:ss')
// 返回值 2017-06-22 四 19:46:14

1. 기본 코드:

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

arg = new Date().getTime(): 여기서는 구조 분해를 사용하여 arg에 기본값을 추가합니다.

2. unix 메소드 구현

 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으로 나누어 반올림해야 하는 밀리초 수를 반환합니다.

3. 정적 unix 메소드 구현

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 }

 Static unixmethod: 매개변수 타임스탬프 밀리초는 Date 객체를 반환합니다.

  새 Date()는 밀리초 매개변수만 허용할 수 있으며 1000을 곱해야 합니다

  

  IV. 형식 방식 구현

 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 Method : 원하는 형식에 맞게 'YYY-MM-DD HH:mm:ss', 'YYY-MM-DD' 등을 전달합니다. get (자세한 내용은 moment.js의 format 메소드를 참고하세요)

 padStart( ) 메소드는 월이나 날짜 앞에 0을 추가하는 것입니다

 

이 시점에서 우리는 unix, static unix, 코드를 완성하려면 github을 확인하세요. 다른 날짜 및 시간 처리 방법을 구현해야 하는 경우 메시지를 남겨주시면 나중에 천천히 개선하여 추가하겠습니다.

위 내용은 moment.js 구현 예시에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.