Get current date with Vue

0

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

  

December 17, 2018

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

The only reference I found was this however it is in pure javascript.

Has anyone ever had to do something like this in Vue?

    
asked by anonymous 17.12.2018 / 12:52

2 answers

6

I do not understand why it can not 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 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 Date.toLocaleDateString() and set it to output 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 logic above in Vue as you see fit.

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><divid="app">
  {{ hoje | date }} <br>
  {{ hoje | date_2 }}
</div>
    
17.12.2018 / 13:05
2

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

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

moment().format('LL');
    
17.12.2018 / 12:54