ISO 8601

作者: 二荣xxx | 来源:发表于2021-02-05 20:49 被阅读0次

ISO 8601

国际标准ISO 8601,是国际标准化组织的日期和时间的表示方法

Date本身API

一般使用ISO 8601带时区的对象,Date.parse的字符串不建议使用
ISO 8601转换

let t = new Date()
console.log(t) // Fri Feb 05 2021 19:58:55 GMT+0800 (中国标准时间)
console.log(t.toISOString) //"2021-02-05T11:58:55.372Z"  Z代表零时区
Date.parse("2021-02-05T11:58:55.372Z") //1612526335372
new Date(1612526335372) //Fri Feb 05 2021 19:58:55 GMT+0800 (中国标准时间)

API示例

beautify (string: string) {
    const d = new Date(Date.parse(string)); 
    console.log(d)
    const y = d.getFullYear();  //年
    const m = d.getMonth(); //月
    const dd = d.getDay(); //日
    const now = new Date();
    console.log(y, m, dd);
}
//Fri Feb 05 2021 08:00:00 GMT+0800 (中国标准时间)
// 2021 1 5 

由于ISO 8601的月份是按零开始计算的,打出来的月份要比实际的少一月

鉴于Date本身的API过于复杂,我们可以使用Date库
有两个库可供我们使用

  • moment.js,(体积较大,不建议使用)
  • dayjs,基于moment.js的库,API和用法基本一致(体积相比小很多)

使用dayjs示例

一天=86400*1000

beautify (string: string) { //string传的是一个时间,例:2021-02-03
    const day = dayjs(string)
    // const now = new Date();
    const now = dayjs() // 与下一行的now兼容
    if (day.isSame(now, 'day')) {
      return '今天'
    } else if (day.isSame(now.subtract(1, 'day'), 'day')) {
    //else if(day.isSame(now.valueOf()-86400*1000),'day') day和现在减一天,是同一天
      return '昨天'
    } else if (day.isSame(now.subtract(2, 'day'), 'day')) {
      return '前天'
    } else if (day.isSame(now, 'year')) { //如果day的年和现在的年相同
      return day.format('M月D日')  //更改day的格式
    } else {
      return day.format('YYYY年M月D日') //Y必须为YY或YYYY, D、M也可以为DD,MM
    }
}

与Date API对比

const d = new Date(Date.parse(string));
    const y = d.getFullYear(); //年
    const m = d.getMonth(); //月
    const dd = d.getDay(); //日
    const now = new Date();
    if (now.getFullYear() === y && now.getMonth() === m && now.getDay() === dd) {
      return '今天';
    } else {
      return string;
    }
}
//较麻烦,建议用dayjs

相关文章

网友评论

      本文标题:ISO 8601

      本文链接:https://www.haomeiwen.com/subject/ooygtltx.html