dayjs使用

dayjs使用

安装

npm install dayjs --save 
mport dayjs from 'dayjs'
dayjs().format()

使用

在这里插入图片描述

  1. 使用字符串拼接时,会触发隐式转换

    ‘*’+dayjs(date) //时间戳

    当使用+运算符进行字符串拼接时,JavaScript会尝试将对象转换为原始值(Primitive Value)。Day.js对象在转换时会调用valueOf()方法,而Day.js的valueOf()默认返回的是时间戳(自1970年1月1日以来的毫秒数)

    • 避免隐式转换

      • 使用模板字符串

        console.log(`*${dayjs(date)}`)
        
      • 使用String函数

         '*' + String(dayjs(date))
        
  2. 显式调用

    console.log('*' + dayjs(date).format('YYYY-MM-DD HH:mm:ss'));
    
  3. unix()方法

    // dayjs.unix() 方法接受的参数是一个以秒为单位的时间戳
    console.log(dayjs.unix(1318781876));
    
  4. 检测是否有效

    // 检测当前 Dayjs 对象是否是一个有效的时间。
    dayjs().isValid()
    
  5. 是否传参的区别

    // dayjs().month() 方法如果不带参数调用,是获取当前日期对象的月份,返回值是从 0 开始计数(0 表示 1 月,1 表示 2 月,以此类推)。
    // 当你传入参数调用,比如 dayjs().month(0) ,它是将日期对象的月份设置为 1 月
    console.log(dayjs().month());
    console.log(dayjs().month(0));
    
  6. date()和set()使用

    //在处理日期中 “日” 相关的频繁操作场景下,代码的可读性较高,也便于维护
    console.log(dayjs().date(1));
    // 在需要批量设置多个日期属性,或者动态根据变量来设置不同日期属性的场景下,set() 方法更具优势
    console.log(dayjs().set('date',1));
    
  7. valueOf()

    // Day.js的valueOf()返回时间戳
    console.log(dayjs(new Date()).valueOf());
    
  8. toString()

    // toString()默认返回ISO格式字符串
    console.log(dayjs(date).toString());
    
  9. add()

    console.log(dayjs().add(7, 'day'));
    
  10. substract()

    console.log(dayjs().subtract(7, 'year'));
    
  11. startOf()

    //会返回本周日的开始时间,从w:0开始
    console.log(dayjs().startOf('week'));
    
  12. endOf()

    // 获取当前时间所在月的最后时刻(月最后一天的23:59:59.999)
    console.log(dayjs().endOf('month'));
    
  13. format

    // 日期字符串并格式化
    console.log(dayjs().format(''));
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值