SoFunction
Updated on 2025-04-06

Several Ways of Vue Time Conversion

VUE time conversion

Working a project will definitely affect many data types, and data types can be converted. Sometimes the time you get from the backend does not meet the standards. At this time, you need to convert it before using it. There are two ways to convert it, depending on which one you personally prefer. Here the time has been converted to an example

Filter filter

Global filter

Writing

// Timestamp filter('dateFormat', (dataStr) => {
  var time = new Date(dataStr)

  function timeAdd0 (str) {
    if (str < 10) {
      str = '0' + str
    }
    return str
  }
  var y = ()
  var m = () + 1
  var d = ()
  var h = ()
  var mm = ()
  var s = ()
  return y + '-' + timeAdd0(m) + '-' + timeAdd0(d) + ' ' + timeAdd0(h) + ':' + timeAdd0(mm) + ':' + timeAdd0(s)
})

At this time the timestamp will become the parameter dataStr for operation

Local filter

In a single vue file, there is the filters attribute, which is parallel to the periodic function.

Note that at this time, filters are not filters, generally one more s than the global one. For example, the difference between global and local components is the same.

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

use

The usage method is the same globally and locally. We just need to add | to the filtered data

&lt;span&gt;Release time:{{|dateFormat}}&lt;/span&gt;

JS reference conversion

Create a js in the utils file for time conversion

export function tempToData(unixtimestamp2) {
  var unixtimestamp = new Date(unixtimestamp2)
  var year = 1900 + ()
  var month = '0' + (() + 1)
  var date = '0' + ()
  var hour = '0' + ()
  var minute = '0' + ()
  var second = '0' + ()
  return year + '-' + ( - 2, ) + '-' + ( - 2, ) +
    ' ' + ( - 2, ) + ':' +
    ( - 2, ) + ':' +
    ( - 2, )
}

When we use it, just refer to js and use it

Global Quotation

Just quote

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

Local citations

Reference in the corresponding vue file

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

How to use

<span>{{ mTempToData() }}</span>

Summarize

Both methods have their own advantages, but I personally prefer the use of filter filters. In the process of learning, you must learn to learn from one example and apply it to other aspects.

More AboutHow to convert vue timePlease check the related links below