moment.js与dayjs安装与使用

JavaScript015

moment.js与dayjs安装与使用,第1张

安装moment

moment 可以在浏览器和Nodejs环境中引入。以浏览器为例

Moment对象长这样子。

它并不会自行转换成时间字符串。

用format方法尝试 转换,它是一个标明了时区的绝对时间

语言的引入

经测试,并没有得到想要的结果。

新建对象的形式

赋值或者取值。赋值传值,取值不传

求一组时间的最大值和最小值

增加、减少相对时间,比如增加7天

格式化

其它方法

这里只是很小一部分方法,其余看官网

http://momentjs.cn/docs/

Day.js被设计用于在浏览器和Node.js中工作。

安装

以浏览器为例,引入

dayjs对象

国际化, dayjs的国际化设置没有问题。

dayjs与moment大同小异。不同的是dayjs实现某些功能需要另外引入插件,dayjs本身提供一个较小的包。

引入插件

大概看看dayjs的一些方法,基本上与moment的方法名是一致的

Day.js 是一个极简的 JavaScript 库,它解析、验证、操作和显示现代浏览器的日期和时间。 官网地址

下面简单介绍一下在vue项目i中如何使用dayjs,具体步骤如下所示:

第一步安装依赖

在main.js中引入dayjs,并将dayjs放到vue原型上

第三步在需要的处理时间的组件中使用dayjs

上面是将年月日和时分秒拆开写的,也可以一起处理,如下图:

这样就得到了我们想要的时间格式

若后台返回格式如下:

let data = [

    {"createdAt": "2020-08-02T11:00:24.580Z", "name": "西瓜"},

    {"createdAt": "2020-08-03T11:00:24.580Z", "name": "水蜜桃"},

    {"createdAt": "2020-08-03T11:00:24.580Z", "name": "樱桃"},

    {"createdAt": "2020-08-02T11:00:24.580Z", "name": "西柚"},

]

      方法:使用 dayjs(createdAt).format('YYYY-MM-DD') 转换

      注:dayjs 安装引用

             npm install dayjs --save     import dayjs from 'dayjs'

     for ( let i=0i<array.lengthi++ ) {      

            let createdAt = dayjs(array[i].time)

            array[i].createdAt = createdAt

    }

 mapName (array) {

          let newArray = []

          array.forEach((item, i) =>{

              let index = -1

              let alreadyExists = newArray.some((newItem, j) =>{

                  if (item.createdAt === newItem.createdAt) {

                      index = j

                      return true

                  }

              })

              if (!alreadyExists) {

                  newArray.push({

                      createdAt: item.createdAt,

                      name: [item.name]

                  })

              } else {

                  newArray[index].price.push(item.name)

              }

          })

          return newArray

      }