前端 处理时间格式,时间戳的转换封装

本文介绍了一个用于处理和格式化日期的JavaScript类,包括日期加减、格式转换、获取特定日期部分等功能,适用于多种日期输入格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先建立个js文件

const WEEK_ARR =  ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
export class DateFormat {
  date
  constructor (date = new Date()) {
    this.date = this.getDate(date)
  }

  getTimestamp (days) {
    return days * 24 * 60 * 60 * 1000
  }

  add (count, type = 'day') {
    switch (type) {
      case 'day':
        this.date = new Date(+this.date + this.getTimestamp(count))
        break
      case 'week':
        this.date = new Date(+this.date + this.getTimestamp(count * 7))
        break
      case 'month':
        const thisMonth = this.date.getMonth()
        // const year = (thisMonth + count)/12 >> 0
        // const month = (thisMonth + count) % 12
        // this.date.setYear(this.date.getFullYear()+year)
        this.date.setMonth(thisMonth + count)
        break
      default:
    }
    return this
  }

  /*
   * @date  可以是时间戳,字符串,Date对象
   */
  getDate (date) {

    if (!date) {
      return new Date()
    }

    if (date instanceof Date ) {
      return date
    }

    if (isNaN(date) && typeof date === 'string') {
      // 2017-01 || 2017/1
      if (/^\d{4}-\d{2}$/.test(date) || /^\d{4}\/\d{2}$/.test(date)) {
        date = `${date}-01`
      }
      return new Date(date.replace(/-/g, '/'))
    }

    if (typeof +date === 'number') {
      return new Date(date)
    }
  }

  isSame (time, type = 'day') {
    if (type === 'day') {
      return this.format('YYYY-MM-DD') === time.format('YYYY-MM-DD')
    } else if (type === 'month') {
      return this.format('YYYY-MM') === time.format('YYYY-MM')
    } else {
      return this.format('YYYY') === time.format('YYYY')
    }
  }

  //timestamp
  timestamp () {
    return +this.date
  }

  //本月第几天
  today () {
    return this.date.getDate()
  }

  //本周第几天
  day () {
    return this.date.getDay()
  }

  month () {
    return this.date.getMonth()
  }

  //当月有几天
  daysInMonth () {
    const date = new Date()
    const currMonth = this.date.getMonth()
    date.setMonth(currMonth + 1)
    date.setDate(0);
    return date.getDate();
  }

  getWeekString () {
    return WEEK_ARR[this.date.getDay()]
  }

  getWeekIndex () {
    return this.date.getDay()
  }

  format (format) {
    const year = this.date.getFullYear()
    const month = this.date.getMonth() + 1
    const day = this.date.getDate()
    //月历考勤
    const signMonth = this.date.getMonth()
    const fullMonth = signMonth > 9 ? signMonth : signMonth == 0  ? 12 : `0${signMonth}`
    const hour = this.date.getHours()
    const minute = this.date.getMinutes()
    const second = this.date.getSeconds()
    const monthStr = month > 9 ? month : `0${month}`
    const dayStr = day > 9 ? day : `0${day}`
    const hourStr = hour > 9 ? hour : `0${hour}`
    const minuteStr = minute > 9 ? minute : `0${minute}`
    const secondStr = second > 9 ? second : `0${second}`
    let result = ''
    switch (format) {
      case 'YYYY':
        result = year
        break
      case 'MM':
        result = monthStr
        break
      case 'M':
        result = month
        break
      case 'DD':
        result = dayStr
        break
      case 'D':
        result = day
        break
      case 'HH':
        result = hourStr
        break
      case 'H':
        result = hour
        break
      case 'mm':
        result = minuteStr
        break
      case 'm':
        result = minute
        break
      case 'ss':
        result = secondStr
        break
      case 's':
        result = second
        break
      case 'HH:mm':
        result = `${hourStr}:${minuteStr}`
        break
      case 'HH:mm:ss':
        result = `${hourStr}:${minuteStr}:${secondStr}`
        break
      //6.12月历考勤新增
      case 'YYYY-MM-R':
        result =  signMonth == 0 ?  `${year - 1}-${fullMonth}` : `${year}-${fullMonth}`
        break
      case 'YYYYMM':
        result = `${year}${monthStr}`
        break
      case 'YYYY-MM':
        result = `${year}-${monthStr}`
        break
      case 'YYYY-MM-DD':
        result = `${year}-${monthStr}-${dayStr}`
        break
      case 'YYYY/MM/DD':
        result = `${year}/${monthStr}/${dayStr}`
        break
      case 'YYYY-M-D':
        result = `${year}-${month}-${day}`
        break
      case 'YYYY-MM-DD HH:mm':
        result =  `${year}-${monthStr}-${dayStr} ${hourStr}:${minuteStr}`
        break
      case 'YYYY-MM-DD HH:mm:ss':
        result =  `${year}-${monthStr}-${dayStr} ${hourStr}:${minuteStr}:${secondStr}`
        break
      case 'YYYY-M-D H:m:s':
        result =  `${year}-${month}-${day} ${hour}:${minute}:${second}`
        break
      case 'YYYY-MM-DD 00:00:00':
        result = `${year}-${monthStr}-${dayStr} 00:00:00`
        break
      case 'MM月':
        result = `${monthStr}`
        break
      case 'M月D日':
        result = `${month}月${day}`
        break
      case 'M.D':
        result = `${month}.${day}`
        break
      case 'MM.DD':
        result = `${monthStr}.${dayStr}`
        break
      case 'YYYY/MM/DD':
        result = `${year}/${monthStr}/${dayStr}`
        break
      case 'YYYY/MM/DD HH:mm':
        result = `${year}/${monthStr}/${dayStr} ${hourStr}:${minuteStr}`
        break
      case 'MM/DD HH:mm':
        result = `${monthStr}/${dayStr} ${hourStr}:${minuteStr}`
        break
      case 'MM月DD日':
        result = `${month}月${day}`
        break
      case 'YYYY年MM月DD日':
        result = `${year}年${month}月${day}`
        break
      case 'YYYY年MM月':
        result = `${year}年${monthStr}`
        break
      case 'MM月DD日 dddd':
        result = `${monthStr}月${dayStr}日 ${this.getWeekString()}`
        break
      case 'YYYY年MM月DD日 dddd':
        result = `${year}年${monthStr}月${dayStr}日 ${this.getWeekString()}`
        break
      case 'MM月DD日 HH:mm':
        result = `${monthStr}月${dayStr}日 ${hourStr}:${minuteStr}`
        break
      case 'YYYY年MM月DD日 HH:mm':
        result = `${year}年${monthStr}月${dayStr}日 ${hourStr}:${minuteStr}`
        break
      case 'YYYY年MM月DD日 HH:mm:ss':
        result = `${year}年${monthStr}月${dayStr}日 ${hourStr}:${minuteStr}:${secondStr}`
        break
    }

    return result
  }

}

export const dateFormat = (date) => new DateFormat(date)

export const getMonthDays = (date) => {
  let  days
  let year = date.split('-')[0]
  let month = date.split('-')[1]
  if(month === '02'){
    days = year % 4 == 0 ? 29 : 28;
  }else if(month == '01' || month == '03' || month == '05' || month == '07' || month == '08' || month == '10' || month == '12') {
    days = 31
  }else {
    days = 30
  }
  return days
}

在组件中引入该文件:

import {dateFormat} from '@/util/DateFormat'

用法很简单 ,根据想要的格式填写就行

let getTimer=dateFormat().format('YYYY-MM-DD HH:mm:ss'),
### 回答1: 前端标准时间格式转换可以使用JavaScript中的Date对象和相关方法来实现。以下是一些常见的时间格式转换: 1. 时间戳转日期时间:可以使用Date对象的构造函数,将时间戳作为参数传入,然后使用相关方法获取对应的年、月、日、小时、分钟、秒等信息,再将它们拼接成需要的格式。 示例代码: ```javascript const timestamp = 1613481600000; // 时间戳,单位为毫秒 const date = new Date(timestamp); const year = date.getFullYear(); const month = date.getMonth() + 1; // 月份从0开始,需要加1 const day = date.getDate(); const hour = date.getHours(); const minute = date.getMinutes(); const second = date.getSeconds(); const formattedTime = `${year}-${month}-${day} ${hour}:${minute}:${second}`; console.log(formattedTime); // 输出:2021-02-16 00:00:00 ``` 2. 日期时间转时间戳:可以使用Date对象的getTime()方法,它会返回当前日期时间的时间戳,单位为毫秒。 示例代码: ```javascript const formattedTime = '2021-02-16 00:00:00'; // 需要转换的日期时间 const timestamp = new Date(formattedTime).getTime(); // 将日期时间转换时间戳 console.log(timestamp); // 输出:1613481600000 ``` 3. 时间格式的格式化:可以使用Date对象的toLocaleDateString()和toLocaleTimeString()方法,它们会返回当前日期时间的本地化格式,可以根据需要自定义参数,如时间的格式、语言等。 示例代码: ```javascript const date = new Date(); const formattedDate = date.toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' }); const formattedTime = date.toLocaleTimeString('zh-CN', { hour12: false, hour: '2-digit', minute: '2-digit', second: '2-digit' }); console.log(formattedDate); // 输出:2023/02/16 console.log(formattedTime); // 输出:13:40:22 ``` 以上是一些常见的时间格式转换方式,可以根据具体需求灵活使用。 ### 回答2: 前端标准时间格式转换包括将不同的时间格式转换为标准的时间格式,以便于在前端页面中显示和处理。常见的时间格式包括年月日时分秒、年月日、时分秒等。 在前端开发中,可以使用JavaScript的Date对象进行时间格式转换。Date对象提供了多个方法和属性,可以方便地进行时间的处理和格式转换。 要将不同的时间格式转换为标准的时间格式,首先需要获取到原始时间的数值,可以使用Date对象的构造函数或者相关方法将字符串类型的时间转换为Date对象。然后,使用Date对象提供的方法,如getFullYear()、getMonth()、getDate()、getHours()、getMinutes()、getSeconds()等获取时间的年、月、日、时、分、秒等信息。 根据需要,可以将获取到的时间信息按照标准时间格式进行拼接,例如:yyyy-MM-dd HH:mm:ss。具体的代码如下: ``` var date = new Date(); // 获取当前时间 var year = date.getFullYear(); // 获取年份 var month = date.getMonth() + 1; // 获取月份(注意要加1,因为JavaScript的月份是从0开始的) var day = date.getDate(); // 获取日期 var hour = date.getHours(); // 获取小时 var minute = date.getMinutes(); // 获取分钟 var second = date.getSeconds(); // 获取秒数 // 格式化时间 var formattedTime = year + '-' + addZero(month) + '-' + addZero(day) + ' ' + addZero(hour) + ':' + addZero(minute) + ':' + addZero(second); // 在页面上显示时间 document.getElementById('time').innerHTML = formattedTime; // 封装一个函数,用于补零 function addZero(num) { return num < 10 ? '0' + num : num; } ``` 以上代码通过调用Date对象的相关方法,获取当前时间的年、月、日、时、分、秒信息,并通过拼接字符串的形式将时间格式化为yyyy-MM-dd HH:mm:ss的标准格式。最后,将格式化后的时间显示在页面上。 这样,前端就可以对不同的时间格式进行转换,使之符合标准的时间格式要求,便于在页面上显示和操作。 ### 回答3: 前端标准时间格式转换指的是将不同格式的时间字符串转换为标准的时间格式。一般来说,前端开发中最常见的时间格式是ISO 8601标准的时间字符串,格式为"YYYY-MM-DDTHH:mm:ss.sssZ"。下面介绍一种常见的方法来进行时间格式转换。 首先,可以使用JavaScript内置的Date对象来解析和处理时间。可以通过传入不同格式的时间字符串(如"2019-01-01"、"2019-01-01T00:00:00"、"2019-01-01T00:00:00.000")来创建一个Date对象。 接着,可以使用Date对象的方法来获取年、月、日、时、分、秒等时间信息,然后根据需要进行格式化输出。可以使用Date对象的getFullYear()、getMonth()、getDate()、getHours()、getMinutes()、getSeconds()等方法获取具体时间。注意,这些方法返回的月份是从0开始的,所以需要在输出时加1。 如果需要将时间格式化输出为特定的格式,例如"YYYY年MM月DD日 HH:mm:ss",可以使用JavaScript的字符串操作函数concat()、padStart()等进行格式化操作。 最后,需要注意的是,不同浏览器对于时间格式的解析和处理可能存在差异,所以在进行时间格式转换时,需要考虑兼容性和测试不同浏览器的表现。 总结起来,前端标准时间格式转换可以使用JavaScript的Date对象来解析和处理时间,然后根据需要进行格式化输出,注意兼容性和浏览器差异。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值