Varias formas de conversión de tiempo vue

Conversión de tiempo

Definitivamente, hacer un proyecto involucrará muchos tipos de datos, y los tipos de datos se pueden convertir. A veces, el tiempo que el front-end obtiene del back-end no cumple con el estándar. En este momento, debe convertirse utilizado. Hay dos conversiones. Depende de cuál prefiera personalmente. Aquí se ha convertido el tiempo en un ejemplo

Filtrar

Filtro global

Escribe en main.js

// 时间戳过滤器
Vue.filter('dateFormat', (dataStr) => {
    
    
  var time = new Date(dataStr)

  function timeAdd0 (str) {
    
    
    if (str < 10) {
    
    
      str = '0' + str
    }
    return str
  }
  var y = time.getFullYear()
  var m = time.getMonth() + 1
  var d = time.getDate()
  var h = time.getHours()
  var mm = time.getMinutes()
  var s = time.getSeconds()
  return y + '-' + timeAdd0(m) + '-' + timeAdd0(d) + ' ' + timeAdd0(h) + ':' + timeAdd0(mm) + ':' + timeAdd0(s)
})

En este momento, la marca de tiempo details.createTime se convertirá en el parámetro dataStr de Vue.filter para el cálculo

Filtro local

En el archivo único de vue, hay un atributo de filtros, que se yuxtapone con funciones periódicas,

Tenga en cuenta que en este momento los filtros no son filtros. A nivel local, generalmente hay uno más que global. Por ejemplo, la diferencia entre componentes globales y locales es la misma.

  created(){
    
    
  },
  filters:{
    
    
      dateFormat:function(dataStr){
    
    
        var time = new Date(dataStr)
        function timeAdd0 (str) {
    
    
          if (str < 10) {
    
    
            str = '0' + str
          }
          return str
        }
        var y = time.getFullYear()
        var m = time.getMonth() + 1
        var d = time.getDate()
        var h = time.getHours()
        var mm = time.getMinutes()
        var s = time.getSeconds()
        return y + '-' + timeAdd0(m) + '-' + timeAdd0(d) + ' ' + timeAdd0(h) + ':' + timeAdd0(mm) + ':' + timeAdd0(s)
       }
  },

usar

El uso es el mismo a nivel global y local, solo necesitamos agregar | después de los datos filtrados.

<span>发布时间:{
   
   {details.createTime|dateFormat}}</span>

Conversión de referencia JS

Construya un js en el archivo utils para la conversión de tiempo

export function tempToData(unixtimestamp2) {
    
    
  var unixtimestamp = new Date(unixtimestamp2)
  var year = 1900 + unixtimestamp.getYear()
  var month = '0' + (unixtimestamp.getMonth() + 1)
  var date = '0' + unixtimestamp.getDate()
  var hour = '0' + unixtimestamp.getHours()
  var minute = '0' + unixtimestamp.getMinutes()
  var second = '0' + unixtimestamp.getSeconds()
  return year + '-' + month.substring(month.length - 2, month.length) + '-' + date.substring(date.length - 2, date.length) +
    ' ' + hour.substring(hour.length - 2, hour.length) + ':' +
    minute.substring(minute.length - 2, minute.length) + ':' +
    second.substring(second.length - 2, second.length)
}

En este momento, cuando lo usemos, solo necesitamos citar js y usarlo.

Referencia global

Solo referencia en main.js

import {
    
     tempToData } from '@/utils/DataUtils'

Referencia local

Referencia en el archivo vue correspondiente

import {
    
     tempToData } from '@/utils/DataUtils'

Cómo utilizar

<span>{
   
   { mTempToData(details.createTime) }}</span>

para resumir

Los dos métodos tienen sus propios méritos, pero yo personalmente prefiero el uso del filtro
En el proceso de aprendizaje, aprenda a sacar inferencias el uno del otro.

Supongo que te gusta

Origin blog.csdn.net/weixin_43236062/article/details/103321625
Recomendado
Clasificación