Catch current date with Vue

Asked

Viewed 1,762 times

0

I need to take the current date and format it the following type:

17 de December de 2018

I’m using the date within a project in Vue.

Only reference I found was this but is in pure javascript.

Someone once had to do something like this in Vue?

  • 1

    Vue is just a Lib to create components. All the Javascript part should be developed by you. Soon this JS code will work ;)

2 answers

9


I don’t understand why it can’t be in pure javascript. After all, Vue.JS is also in pure javascript, just use the code in the framework.


You can create an array with the name of the months and get the correct name using the result of Date.getMonth() as an index.

function formatDate(date) {
  let dia = date.getDate()
  let mes = [
    'janeiro', 'fevereiro', 'março', 'abril',
    'maio', 'junho', 'julho', 'agosto', 'setembro', 
    'outubro', 'novembro', 'dezembro'
  ][date.getMonth()]
  let ano = date.getFullYear()
  
  return `${dia} de ${mes} de ${ano}`
}

let hoje = new Date()

console.log(formatDate(hoje))


If browser compatibility is not an issue, you can use the method Date.toLocaleDateString() and configure so that the output is the one you want:

let hoje = new Date()
let data_formatada = hoje.toLocaleDateString('pt-BR', {
  day: 'numeric',
  month: 'long',
  year: 'numeric'
})

console.log(data_formatada)


You can use the above logic in Vue as well as understand.

function formatDate(date) {
  let dia = date.getDate()
  let mes = [
    'janeiro', 'fevereiro', 'março', 'abril',
    'maio', 'junho', 'julho', 'agosto', 'setembro', 
    'outubro', 'novembro', 'dezembro'
  ][date.getMonth()]
  let ano = date.getFullYear()
  
  return `${dia} de ${mes} de ${ano}`
}

let formatter = new Intl.DateTimeFormat('pt-BR', {
  day: 'numeric',
  month: 'long',
  year: 'numeric'
})

new Vue({
  el: '#app',
  data:{
    hoje: new Date()
  },
  filters: {
    date: formatDate,
    date_2: formatter.format
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  {{ hoje | date }} <br>
  {{ hoje | date_2 }}
</div>

2

To work with dates in Javascript I believe that the best option is the Moment.

It matters it, then to do what you need just one.

moment().format('LL');

Browser other questions tagged

You are not signed in. Login or sign up in order to post.